Files
p2ns/docs/plugins/example.plugin.md
T
2025-12-17 20:05:50 -05:00

5.2 KiB
Raw Blame History

Example Plugin

A comprehensive template plugin for P2NS. Use this as a starting point when creating new plugins.

Overview

The Example Plugin demonstrates all the key features available to P2NS plugins:

  • Basic HTTP request handling
  • Static file serving from www/ directory
  • API endpoints with query parameters
  • Plugin lifecycle hooks (onInit, onShutdown)
  • Admin panel settings integration
  • Admin panel actions integration
  • Using settings in handlers and frontend

Features Demonstrated

Admin Settings

The plugin registers four example settings that appear in the P2NS admin panel:

Setting Type Description
exampleString string Greeting prefix used in API responses
exampleNumber number Multiplier used in calculations (1-1000)
exampleBoolean boolean Toggle to include timestamps in responses
exampleSelect select Operation mode selector (Standard/Enhanced/Advanced)

Admin Actions

The plugin registers three actions callable from the admin panel:

Action Description
Test Action Demonstrates using current settings in an action
Reset Data Clears action history and cached data
Calculate Performs calculation using the multiplier setting

API Endpoints

GET /api/hello

Returns a greeting message using the configured greeting prefix.

Query Parameters:

  • name (optional): Name to greet (default: "World")

Response:

{
  "message": "Hello, World!",
  "timestamp": "2025-01-01T00:00:00.000Z"
}

Note: timestamp is only included if exampleBoolean is true.

GET /api/info

Returns plugin information and current settings.

Response:

{
  "plugin": "example.plugin",
  "version": "1.0.0",
  "description": "A comprehensive template plugin...",
  "dnsReady": true,
  "connectedPeers": 5,
  "settings": {
    "exampleString": "Hello, World!",
    "exampleNumber": 42,
    "exampleBoolean": false,
    "exampleSelect": "option1"
  }
}

GET /api/calculate

Performs a calculation using the multiplier setting.

Query Parameters:

  • value (optional): Number to multiply (default: 0)

Response:

{
  "input": 10,
  "multiplier": 42,
  "result": 420,
  "calculation": "10 × 42 = 420"
}

GET /api/mode

Returns the current operation mode and available modes.

Response:

{
  "mode": "option1",
  "description": "Standard mode - basic functionality",
  "availableModes": ["option1", "option2", "option3"]
}

GET /api/public-key

Returns the local peer's public key.

Response:

{
  "publicKey": "abc123...",
  "hasIdentity": true
}

GET /api/actions

Returns the action history and last action result.

Response:

{
  "lastResult": { ... },
  "history": [ ... ]
}

GET /api/settings

Returns all current plugin settings.

Response:

{
  "settings": { ... },
  "timestamp": "2025-01-01T00:00:00.000Z"
}

File Structure

example.plugin/
├── config.json      # Plugin configuration
├── index.js         # Backend handler with API logic
├── README.md        # Plugin documentation
├── app.log          # Plugin log file (auto-generated)
└── www/             # Frontend files
    ├── index.html   # Main HTML page
    ├── icon.svg     # Plugin icon
    ├── manifest.json
    └── css/
        └── style.css

Creating Your Own Plugin

  1. Copy this plugin directory to plugin-sites/your.domain/

  2. Update config.json:

    {
      "name": "Your Plugin",
      "version": "1.0.0",
      "domain": "your.domain",
      "enabled": true,
      "description": "Description of your plugin",
      "author": "Your Name",
      "www": "www"
    }
    
  3. Modify index.js:

    • Update the handler to serve your API endpoints
    • Register your own settings in onInit()
    • Register your own actions in onInit()
    • Add cleanup logic in onShutdown() if needed
  4. Update www/index.html with your frontend

  5. Restart P2NS - your plugin will be automatically discovered

Plugin SDK Usage

This plugin demonstrates key SDK features:

const sdk = require('../../includes/plugins/sdk');

// Parse requests
const { path, query, method } = sdk.router.parseRequest(req);

// Send JSON responses
return sdk.router.json(res, { data: 'value' });

// Check system state
if (sdk.utils.isDNSReady()) { ... }
const peers = sdk.state.connectedPeers;

// Register settings
sdk.admin.registerSetting('key', {
  type: 'string',
  label: 'Label',
  description: 'Description',
  default: 'default value'
});

// Get settings
const value = await sdk.admin.getSetting('key', 'default');

// Register actions
sdk.admin.registerAction('actionName', async (params) => {
  return { success: true, message: 'Done!' };
}, {
  label: 'Action Label',
  description: 'What this action does',
  icon: '🚀'
});

// Logging
sdk.log.info('my.plugin', 'Message');
sdk.log.error('my.plugin', 'Error message');

License

MIT