Fix Uptime Kuma integration and add interactive UI
Some checks failed
Build and Push Container / build (push) Has been cancelled

- Switch to uptime-kuma-api library (Socket.io based)
- Add Approve & Run buttons for Claude's additional commands
- Add answer input fields for Claude's questions
- Add push monitor type support

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Debian
2026-01-05 03:16:19 +00:00
parent 75f8ead736
commit a034842cd3
4 changed files with 160 additions and 92 deletions

View File

@@ -7,3 +7,4 @@ requests==2.31.0
python-dotenv==1.0.0 python-dotenv==1.0.0
gevent==23.9.1 gevent==23.9.1
gevent-websocket==0.10.1 gevent-websocket==0.10.1
uptime-kuma-api==1.2.1

View File

@@ -1,15 +1,26 @@
from typing import Optional from typing import Optional
from dataclasses import dataclass, asdict from dataclasses import dataclass
import requests from uptime_kuma_api import UptimeKumaApi, MonitorType
from config import get_config from config import get_config
# Map our monitor types to Uptime Kuma types
TYPE_MAP = {
"http": MonitorType.HTTP,
"tcp": MonitorType.PORT,
"ping": MonitorType.PING,
"docker": MonitorType.DOCKER,
"keyword": MonitorType.KEYWORD,
"push": MonitorType.PUSH,
}
@dataclass @dataclass
class Monitor: class Monitor:
"""Uptime Kuma monitor configuration.""" """Uptime Kuma monitor configuration."""
type: str # http, tcp, ping, docker, keyword type: str # http, tcp, ping, docker, keyword, push
name: str name: str
url: Optional[str] = None # For HTTP monitors url: Optional[str] = None # For HTTP monitors
hostname: Optional[str] = None # For TCP/Ping monitors hostname: Optional[str] = None # For TCP/Ping monitors
@@ -18,147 +29,143 @@ class Monitor:
keyword: Optional[str] = None # For keyword monitors keyword: Optional[str] = None # For keyword monitors
docker_container: Optional[str] = None # For Docker monitors docker_container: Optional[str] = None # For Docker monitors
docker_host: Optional[str] = None # For Docker monitors docker_host: Optional[str] = None # For Docker monitors
push_token: Optional[str] = None # For Push monitors
retries: int = 3 retries: int = 3
retry_interval: int = 60 retry_interval: int = 60
max_redirects: int = 10 max_redirects: int = 10
accepted_statuscodes: list[str] = None accepted_statuscodes: list[str] = None
notification_id_list: Optional[list[int]] = None
def __post_init__(self): def __post_init__(self):
if self.accepted_statuscodes is None: if self.accepted_statuscodes is None:
self.accepted_statuscodes = ["200-299"] self.accepted_statuscodes = ["200-299"]
def to_api_format(self) -> dict:
"""Convert to Uptime Kuma API format."""
# Map our types to Kuma's type values
type_map = {
"http": "http",
"tcp": "port",
"ping": "ping",
"docker": "docker",
"keyword": "keyword",
}
data = {
"type": type_map.get(self.type, self.type),
"name": self.name,
"interval": self.interval,
"retries": self.retries,
"retryInterval": self.retry_interval,
"maxredirects": self.max_redirects,
"accepted_statuscodes": self.accepted_statuscodes,
}
if self.url:
data["url"] = self.url
if self.hostname:
data["hostname"] = self.hostname
if self.port:
data["port"] = self.port
if self.keyword:
data["keyword"] = self.keyword
if self.docker_container:
data["docker_container"] = self.docker_container
if self.docker_host:
data["docker_host"] = self.docker_host
if self.notification_id_list:
data["notificationIDList"] = self.notification_id_list
return data
class UptimeKumaClient: class UptimeKumaClient:
"""Client for Uptime Kuma REST API.""" """Client for Uptime Kuma using Socket.io API."""
def __init__(self): def __init__(self):
config = get_config() config = get_config()
self.base_url = config.uptime_kuma_url.rstrip("/") self.base_url = config.uptime_kuma_url.rstrip("/")
self.api_key = config.uptime_kuma_api_key self.api_key = config.uptime_kuma_api_key
self.session = requests.Session() self._api = None
self.session.headers.update({
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
})
def _request(self, method: str, endpoint: str, **kwargs) -> dict: def _get_api(self) -> UptimeKumaApi:
"""Make an API request.""" """Get connected API instance."""
url = f"{self.base_url}/api{endpoint}" if self._api is None:
response = self.session.request(method, url, **kwargs) self._api = UptimeKumaApi(self.base_url)
response.raise_for_status() # Login with API key as token
return response.json() if response.content else {} self._api.login_by_token(self.api_key)
return self._api
def _disconnect(self):
"""Disconnect API."""
if self._api:
try:
self._api.disconnect()
except Exception:
pass
self._api = None
def get_monitors(self) -> list[dict]: def get_monitors(self) -> list[dict]:
"""Get all monitors.""" """Get all monitors."""
try: try:
result = self._request("GET", "/monitors") api = self._get_api()
return result.get("monitors", []) return api.get_monitors()
except Exception as e: except Exception as e:
self._disconnect()
raise Exception(f"Failed to get monitors: {str(e)}") raise Exception(f"Failed to get monitors: {str(e)}")
def get_monitor(self, monitor_id: int) -> dict: def get_monitor(self, monitor_id: int) -> dict:
"""Get a specific monitor.""" """Get a specific monitor."""
try: try:
result = self._request("GET", f"/monitors/{monitor_id}") api = self._get_api()
return result.get("monitor", {}) return api.get_monitor(monitor_id)
except Exception as e: except Exception as e:
self._disconnect()
raise Exception(f"Failed to get monitor {monitor_id}: {str(e)}") raise Exception(f"Failed to get monitor {monitor_id}: {str(e)}")
def create_monitor(self, monitor: Monitor) -> dict: def create_monitor(self, monitor: Monitor) -> dict:
"""Create a new monitor.""" """Create a new monitor."""
try: try:
data = monitor.to_api_format() api = self._get_api()
result = self._request("POST", "/monitors", json=data)
return result
except Exception as e:
raise Exception(f"Failed to create monitor: {str(e)}")
def update_monitor(self, monitor_id: int, monitor: Monitor) -> dict: monitor_type = TYPE_MAP.get(monitor.type)
"""Update an existing monitor.""" if not monitor_type:
try: raise ValueError(f"Unknown monitor type: {monitor.type}")
data = monitor.to_api_format()
result = self._request("PUT", f"/monitors/{monitor_id}", json=data) kwargs = {
"type": monitor_type,
"name": monitor.name,
"interval": monitor.interval,
"maxretries": monitor.retries,
"retryInterval": monitor.retry_interval,
}
# Add type-specific fields
if monitor.type == "http":
kwargs["url"] = monitor.url
kwargs["maxredirects"] = monitor.max_redirects
kwargs["accepted_statuscodes"] = monitor.accepted_statuscodes
elif monitor.type == "keyword":
kwargs["url"] = monitor.url
kwargs["keyword"] = monitor.keyword
elif monitor.type == "tcp":
kwargs["hostname"] = monitor.hostname
kwargs["port"] = monitor.port
elif monitor.type == "ping":
kwargs["hostname"] = monitor.hostname
elif monitor.type == "docker":
kwargs["docker_container"] = monitor.docker_container
if monitor.docker_host:
kwargs["docker_host"] = monitor.docker_host
elif monitor.type == "push":
# Push monitors are created and get a token back
pass
result = api.add_monitor(**kwargs)
return result return result
except Exception as e: except Exception as e:
raise Exception(f"Failed to update monitor {monitor_id}: {str(e)}") self._disconnect()
raise Exception(f"Failed to create monitor: {str(e)}")
def delete_monitor(self, monitor_id: int) -> dict: def delete_monitor(self, monitor_id: int) -> dict:
"""Delete a monitor.""" """Delete a monitor."""
try: try:
result = self._request("DELETE", f"/monitors/{monitor_id}") api = self._get_api()
result = api.delete_monitor(monitor_id)
return result return result
except Exception as e: except Exception as e:
self._disconnect()
raise Exception(f"Failed to delete monitor {monitor_id}: {str(e)}") raise Exception(f"Failed to delete monitor {monitor_id}: {str(e)}")
def pause_monitor(self, monitor_id: int) -> dict: def pause_monitor(self, monitor_id: int) -> dict:
"""Pause a monitor.""" """Pause a monitor."""
try: try:
result = self._request("POST", f"/monitors/{monitor_id}/pause") api = self._get_api()
result = api.pause_monitor(monitor_id)
return result return result
except Exception as e: except Exception as e:
self._disconnect()
raise Exception(f"Failed to pause monitor {monitor_id}: {str(e)}") raise Exception(f"Failed to pause monitor {monitor_id}: {str(e)}")
def resume_monitor(self, monitor_id: int) -> dict: def resume_monitor(self, monitor_id: int) -> dict:
"""Resume a paused monitor.""" """Resume a paused monitor."""
try: try:
result = self._request("POST", f"/monitors/{monitor_id}/resume") api = self._get_api()
result = api.resume_monitor(monitor_id)
return result return result
except Exception as e: except Exception as e:
self._disconnect()
raise Exception(f"Failed to resume monitor {monitor_id}: {str(e)}") raise Exception(f"Failed to resume monitor {monitor_id}: {str(e)}")
def get_status(self) -> dict:
"""Get Uptime Kuma status/info."""
try:
result = self._request("GET", "/status-page")
return result
except Exception as e:
raise Exception(f"Failed to get status: {str(e)}")
def test_connection(self) -> bool: def test_connection(self) -> bool:
"""Test connection to Uptime Kuma.""" """Test connection to Uptime Kuma."""
try: try:
self._request("GET", "/monitors") api = self._get_api()
api.get_monitors()
return True return True
except Exception: except Exception:
self._disconnect()
return False return False

View File

@@ -134,6 +134,13 @@ export default function Dashboard({ scanProgress, scanResults, analysisResults,
scan={currentScan} scan={currentScan}
analysis={currentAnalysis} analysis={currentAnalysis}
devMode={devMode} devMode={devMode}
onCommandApproved={async (command) => {
await api.runCommand(currentScanId, command, 'User approved from UI');
}}
onQuestionAnswered={async (question, answer) => {
// TODO: Implement question answering API
console.log('Question answered:', question, answer);
}}
/> />
)} )}
</div> </div>

View File

@@ -1,11 +1,34 @@
import { useState } from 'react'; import { useState } from 'react';
import { api } from '../api/client'; import { api } from '../api/client';
export default function DiscoveryResults({ scanId, scan, analysis, devMode }) { export default function DiscoveryResults({ scanId, scan, analysis, devMode, onCommandApproved, onQuestionAnswered }) {
const [selectedMonitors, setSelectedMonitors] = useState([]); const [selectedMonitors, setSelectedMonitors] = useState([]);
const [creatingDefaults, setCreatingDefaults] = useState(false); const [creatingDefaults, setCreatingDefaults] = useState(false);
const [creatingSuggested, setCreatingSuggested] = useState(false); const [creatingSuggested, setCreatingSuggested] = useState(false);
const [createResults, setCreateResults] = useState(null); const [createResults, setCreateResults] = useState(null);
const [runningCommands, setRunningCommands] = useState({});
const [questionAnswers, setQuestionAnswers] = useState({});
const handleRunCommand = async (command, index) => {
setRunningCommands(prev => ({ ...prev, [index]: true }));
try {
if (onCommandApproved) {
await onCommandApproved(command);
}
} finally {
setRunningCommands(prev => ({ ...prev, [index]: false }));
}
};
const handleAnswerQuestion = async (question, index) => {
const answer = questionAnswers[index];
if (!answer || !answer.trim()) return;
if (onQuestionAnswered) {
await onQuestionAnswered(question, answer);
}
setQuestionAnswers(prev => ({ ...prev, [index]: '' }));
};
const handleCreateDefaults = async () => { const handleCreateDefaults = async () => {
setCreatingDefaults(true); setCreatingDefaults(true);
@@ -210,11 +233,22 @@ export default function DiscoveryResults({ scanId, scan, analysis, devMode }) {
<div className="space-y-2"> <div className="space-y-2">
{analysis.additional_commands.map((cmd, index) => ( {analysis.additional_commands.map((cmd, index) => (
<div key={index} className="p-3 bg-slate-700/50 rounded"> <div key={index} className="p-3 bg-slate-700/50 rounded">
<div className="flex items-start justify-between gap-3">
<div className="flex-1">
<code className="text-sm text-green-400 font-mono block mb-1"> <code className="text-sm text-green-400 font-mono block mb-1">
{cmd.command} {cmd.command}
</code> </code>
<p className="text-xs text-slate-400">{cmd.reason}</p> <p className="text-xs text-slate-400">{cmd.reason}</p>
</div> </div>
<button
onClick={() => handleRunCommand(cmd.command, index)}
disabled={runningCommands[index]}
className="px-3 py-1 text-sm bg-amber-600 hover:bg-amber-500 disabled:bg-slate-600 text-white rounded transition-colors whitespace-nowrap"
>
{runningCommands[index] ? 'Running...' : 'Approve & Run'}
</button>
</div>
</div>
))} ))}
</div> </div>
</div> </div>
@@ -224,14 +258,33 @@ export default function DiscoveryResults({ scanId, scan, analysis, devMode }) {
{analysis.questions && analysis.questions.length > 0 && ( {analysis.questions && analysis.questions.length > 0 && (
<div> <div>
<h4 className="font-medium mb-3">Questions from Claude</h4> <h4 className="font-medium mb-3">Questions from Claude</h4>
<ul className="space-y-2"> <div className="space-y-3">
{analysis.questions.map((question, index) => ( {analysis.questions.map((question, index) => (
<li key={index} className="text-sm text-slate-300 flex items-start gap-2"> <div key={index} className="p-3 bg-slate-700/50 rounded">
<p className="text-sm text-slate-300 mb-2 flex items-start gap-2">
<span className="text-purple-400">?</span> <span className="text-purple-400">?</span>
{question} {question}
</li> </p>
<div className="flex gap-2">
<input
type="text"
value={questionAnswers[index] || ''}
onChange={(e) => setQuestionAnswers(prev => ({ ...prev, [index]: e.target.value }))}
placeholder="Type your answer..."
className="flex-1 px-3 py-1 text-sm bg-slate-800 border border-slate-600 rounded focus:outline-none focus:border-purple-500"
onKeyDown={(e) => e.key === 'Enter' && handleAnswerQuestion(question, index)}
/>
<button
onClick={() => handleAnswerQuestion(question, index)}
disabled={!questionAnswers[index]?.trim()}
className="px-3 py-1 text-sm bg-purple-600 hover:bg-purple-500 disabled:bg-slate-600 text-white rounded transition-colors"
>
Answer
</button>
</div>
</div>
))} ))}
</ul> </div>
</div> </div>
)} )}
</div> </div>