sinask/laravel-kuma-api 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sinask/laravel-kuma-api

最新稳定版本:1.0.1

Composer 安装命令:

composer require sinask/laravel-kuma-api

包简介

Laravel wrapper for the Uptime Kuma API

README 文档

README

A comprehensive Laravel package for interacting with Uptime Kuma monitoring systems. This package provides a fluent, Laravel-friendly API client for managing monitors, notifications, status pages, maintenance windows, and more.

Features

  • Full CRUD operations for monitors, notifications, proxies, tags, and more
  • Status page management with incident reporting
  • Maintenance window scheduling
  • Docker host integration
  • API key management
  • 2FA support
  • Database backup and management
  • Strongly-typed enums for monitor types, notification providers, etc.
  • Data Transfer Objects (DTOs) for type-safe data handling
  • Laravel Facade for convenient access
  • Auto-authentication with configured credentials

Requirements

  • PHP 8.2+
  • Laravel 10.x, 11.x, or 12.x
  • Uptime Kuma 1.21+

Installation

Install the package via Composer:

composer require sinask/laravel-kuma-api

Configuration

Publish the configuration file:

php artisan vendor:publish --tag=uptime-kuma-config

Add your Uptime Kuma credentials to your .env file:

UPTIME_KUMA_URL=http://your-uptime-kuma-server:3001
UPTIME_KUMA_USERNAME=admin
UPTIME_KUMA_PASSWORD=your-password
UPTIME_KUMA_TOKEN=       # Optional: 2FA token if enabled

The configuration file (config/uptime-kuma.php):

return [
    'base_url' => env('UPTIME_KUMA_URL', 'http://127.0.0.1:3001'),
    'username' => env('UPTIME_KUMA_USERNAME'),
    'password' => env('UPTIME_KUMA_PASSWORD'),
    'two_factor_token' => env('UPTIME_KUMA_TOKEN'),
];

Basic Usage

Using the Facade

use UptimeKuma\LaravelApi\Facades\UptimeKuma;
use UptimeKuma\LaravelApi\Support\MonitorType;

// Get all monitors
$monitors = UptimeKuma::monitors();

// Get a specific monitor
$monitor = UptimeKuma::monitor(1);

// Create a new HTTP monitor
UptimeKuma::createMonitor([
    'name' => 'My Website',
    'type' => MonitorType::HTTP->value,
    'url' => 'https://example.com',
    'interval' => 60,
]);

// Pause/Resume a monitor
UptimeKuma::pauseMonitor(1);
UptimeKuma::resumeMonitor(1);

// Delete a monitor
UptimeKuma::deleteMonitor(1);

Using Dependency Injection

use UptimeKuma\LaravelApi\Http\UptimeKumaClient;

class MonitorController extends Controller
{
    public function __construct(
        private UptimeKumaClient $client
    ) {}

    public function index()
    {
        return $this->client->monitors();
    }
}

Monitor Types

The package includes all monitor types supported by Uptime Kuma:

use UptimeKuma\LaravelApi\Support\MonitorType;

MonitorType::HTTP;          // HTTP(s) monitoring
MonitorType::KEYWORD;       // HTTP(s) with keyword check
MonitorType::JSON_QUERY;    // HTTP(s) with JSON query
MonitorType::PING;          // Ping monitoring
MonitorType::PORT;          // TCP Port monitoring
MonitorType::DNS;           // DNS monitoring
MonitorType::PUSH;          // Push monitoring
MonitorType::DOCKER;        // Docker container monitoring
MonitorType::STEAM;         // Steam game server
MonitorType::GAMEDIG;       // Game server (GameDig)
MonitorType::MQTT;          // MQTT broker
MonitorType::POSTGRES;      // PostgreSQL
MonitorType::MYSQL;         // MySQL/MariaDB
MonitorType::MONGODB;       // MongoDB
MonitorType::SQLSERVER;     // Microsoft SQL Server
MonitorType::REDIS;         // Redis
MonitorType::RADIUS;        // RADIUS
MonitorType::GRPC_KEYWORD;  // gRPC with keyword
MonitorType::REAL_BROWSER;  // Real browser (Chrome/Chromium)
MonitorType::KAFKA_PRODUCER;// Kafka Producer
MonitorType::TAILSCALE_PING;// Tailscale Ping
MonitorType::GROUP;         // Monitor Group

Notifications

Managing Notifications

use UptimeKuma\LaravelApi\Support\NotificationType;

// Get all notifications
$notifications = UptimeKuma::notifications();

// Create a Discord notification
UptimeKuma::createNotification([
    'name' => 'Discord Alerts',
    'type' => NotificationType::DISCORD->value,
    'isDefault' => true,
    'discordWebhookUrl' => 'https://discord.com/api/webhooks/...',
]);

// Create a Slack notification
UptimeKuma::createNotification([
    'name' => 'Slack Alerts',
    'type' => NotificationType::SLACK->value,
    'slackwebhookURL' => 'https://hooks.slack.com/services/...',
]);

// Test a notification
UptimeKuma::testNotification([
    'type' => NotificationType::TELEGRAM->value,
    'telegramBotToken' => 'your-bot-token',
    'telegramChatID' => 'your-chat-id',
]);

Supported Notification Providers (53+)

Discord, Slack, Telegram, Email (SMTP), Teams, PagerDuty, OpsGenie, Pushover, Gotify, ntfy, Matrix, Mattermost, Rocket.Chat, Twilio, Webhook, and many more.

Status Pages

// Get all status pages
$pages = UptimeKuma::statusPages();

// Create a status page
UptimeKuma::createStatusPage('my-status', 'My Service Status');

// Update a status page
UptimeKuma::updateStatusPage('my-status', [
    'title' => 'Updated Title',
    'description' => 'Service status dashboard',
    'published' => true,
    'showTags' => true,
]);

// Post an incident
UptimeKuma::postIncident('my-status',
    'Service Degradation',
    'We are investigating reports of slow response times.',
    'warning'  // info, warning, danger, primary, light, dark
);

// Remove incident
UptimeKuma::unpinIncident('my-status');

// Delete status page
UptimeKuma::deleteStatusPage('my-status');

Maintenance Windows

use UptimeKuma\LaravelApi\Support\MaintenanceStrategy;

// Get all maintenance windows
$maintenances = UptimeKuma::maintenances();

// Create a scheduled maintenance
UptimeKuma::createMaintenance([
    'title' => 'Weekly Maintenance',
    'description' => 'Regular system maintenance',
    'strategy' => MaintenanceStrategy::RECURRING_WEEKDAY->value,
    'active' => true,
    'weekdays' => [0], // Sunday
    'timeRange' => ['02:00', '04:00'],
]);

// Pause/Resume maintenance
UptimeKuma::pauseMaintenance(1);
UptimeKuma::resumeMaintenance(1);

Tags

// Get all tags
$tags = UptimeKuma::tags();

// Create a tag
UptimeKuma::createTag('Production', '#ff0000');

// Add tag to a monitor
UptimeKuma::addMonitorTag(
    tagId: 1,
    monitorId: 5,
    value: 'optional-value'
);

// Remove tag from monitor
UptimeKuma::deleteMonitorTag(1, 5);

Proxies

use UptimeKuma\LaravelApi\Support\ProxyProtocol;

// Get all proxies
$proxies = UptimeKuma::proxies();

// Create a proxy
UptimeKuma::createProxy([
    'protocol' => ProxyProtocol::SOCKS5->value,
    'host' => 'proxy.example.com',
    'port' => 1080,
    'auth' => true,
    'username' => 'user',
    'password' => 'pass',
    'active' => true,
]);

Docker Hosts

use UptimeKuma\LaravelApi\Support\DockerType;

// Get Docker hosts
$hosts = UptimeKuma::dockerHosts();

// Add a Docker host
UptimeKuma::createDockerHost([
    'name' => 'Local Docker',
    'dockerType' => DockerType::SOCKET->value,
    'dockerDaemon' => '/var/run/docker.sock',
]);

// Test connection
UptimeKuma::testDockerHost([
    'dockerType' => DockerType::TCP->value,
    'dockerDaemon' => 'tcp://192.168.1.100:2375',
]);

Metrics & Heartbeats

// Get heartbeats for a monitor
$heartbeats = UptimeKuma::heartbeats(monitorId: 1, hours: 24);

// Get important heartbeats (status changes)
$important = UptimeKuma::importantHeartbeats(1);

// Get average ping times
$avgPing = UptimeKuma::avgPing();

// Get uptime statistics
$uptime = UptimeKuma::uptime();

// Get SSL certificate info
$certInfo = UptimeKuma::certInfo();

Push Monitors

For push-type monitors, you can send heartbeats from your application:

// Send a successful heartbeat
UptimeKuma::sendHeartbeat(
    pushToken: 'your-push-token',
    status: 'up',
    msg: 'OK',
    ping: 50
);

// Send a failure heartbeat
UptimeKuma::sendHeartbeat(
    pushToken: 'your-push-token',
    status: 'down',
    msg: 'Database connection failed'
);

API Keys

// Get all API keys
$apiKeys = UptimeKuma::apiKeys();

// Create an API key
$key = UptimeKuma::createApiKey(
    name: 'CI/CD Integration',
    expires: '2025-12-31',
    active: true
);

// Delete an API key
UptimeKuma::deleteApiKey(1);

Settings & Database

// Get settings
$settings = UptimeKuma::settings();

// Update settings
UptimeKuma::updateSettings([
    'primaryBaseURL' => 'https://status.example.com',
]);

// Change password
UptimeKuma::changePassword('current-password', 'new-password');

// Database operations
$size = UptimeKuma::databaseSize();
UptimeKuma::shrinkDatabase();

// Backup
$backup = UptimeKuma::exportBackup();
UptimeKuma::importBackup($backupData);

// Clear data
UptimeKuma::clearEvents();
UptimeKuma::clearStatistics();

Two-Factor Authentication

// Check 2FA status
$status = UptimeKuma::status2FA();

// Setup 2FA
$setup = UptimeKuma::prepare2FA('your-password');
// Returns QR code and secret

// Verify token
UptimeKuma::verify2FA('123456');

// Enable 2FA
UptimeKuma::save2FA('your-password');

// Disable 2FA
UptimeKuma::disable2FA('your-password');

Data Transfer Objects

The package includes DTOs for type-safe data handling:

use UptimeKuma\LaravelApi\Data\Monitor;
use UptimeKuma\LaravelApi\Data\Notification;
use UptimeKuma\LaravelApi\Data\Heartbeat;
use UptimeKuma\LaravelApi\Data\StatusPage;
use UptimeKuma\LaravelApi\Data\Maintenance;
use UptimeKuma\LaravelApi\Data\Tag;
use UptimeKuma\LaravelApi\Data\Proxy;
use UptimeKuma\LaravelApi\Data\DockerHost;
use UptimeKuma\LaravelApi\Data\ApiKey;

// Create from API response
$monitor = Monitor::fromArray($response);
echo $monitor->name;
echo $monitor->type->value;

// Convert to array
$data = $monitor->toArray();

Error Handling

use UptimeKuma\LaravelApi\Exceptions\UptimeKumaException;
use UptimeKuma\LaravelApi\Exceptions\AuthenticationException;

try {
    $monitors = UptimeKuma::monitors();
} catch (AuthenticationException $e) {
    // Handle authentication errors
    Log::error('Authentication failed: ' . $e->getMessage());
} catch (UptimeKumaException $e) {
    // Handle other API errors
    Log::error('API error: ' . $e->getMessage());
}

Using a Different Token

// Create a client with a specific token
$client = UptimeKuma::usingToken('your-api-token');
$monitors = $client->monitors();

Testing

Run the test suite:

composer test

The test suite uses mocked HTTP responses and does not require a running Uptime Kuma instance.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This package is open-sourced software licensed under the MIT license.

Credits

统计信息

  • 总下载量: 1
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-08