feat: finish project basic structure and core functions

This commit is contained in:
2026-08-03 22:15:53 +08:00
parent 3ab175b595
commit 19b69acc29
29 changed files with 3864 additions and 2 deletions
+165
View File
@@ -0,0 +1,165 @@
package controller
import (
"fmt"
"strings"
"sync"
"nukumizu-backend/config"
"nukumizu-backend/internal/node"
"nukumizu-backend/internal/template"
"nukumizu-backend/postLog"
)
// Command represents a parsed bot command.
type Command struct {
RawText string
Command string // The command word (e.g., "list", "status")
Args []string // Command arguments
ChatID int64 // Chat/group ID where the command was issued
ChatType string // "group" or "private"
SenderID int64 // User ID of the sender
}
// Controller defines the interface for all notification/bot controllers.
type Controller interface {
Name() string
Start() error
Stop()
IsEnabled() bool
SendStatusChange(change node.StatusChange) error
SendServerList(onlineServers, offlineServers string) error
SendExecuteResult(serverName, serverUUID, command, result string) error
}
// CommandController extends Controller for bidirectional channels (QQ, Telegram).
type CommandController interface {
Controller
HandleCommand(cmd Command) (response string, err error)
}
// Manager manages all controller instances and routes events.
type Manager struct {
mu sync.RWMutex
controllers map[string]Controller
}
var globalManager *Manager
// InitManager initializes the global controller manager.
func InitManager() {
globalManager = &Manager{
controllers: make(map[string]Controller),
}
postLog.Info("Controller manager initialized")
}
// GetManager returns the global controller manager.
func GetManager() *Manager {
return globalManager
}
// GetController returns a specific controller by name.
func GetController(name string) Controller {
if globalManager == nil {
return nil
}
globalManager.mu.RLock()
defer globalManager.mu.RUnlock()
return globalManager.controllers[name]
}
// Register adds a controller to the manager.
func (m *Manager) Register(c Controller) {
m.mu.Lock()
defer m.mu.Unlock()
m.controllers[c.Name()] = c
postLog.Info("Controller registered: " + c.Name())
}
// NotifyStatusChange sends a status change notification to all enabled controllers.
func (m *Manager) NotifyStatusChange(change node.StatusChange) {
m.mu.RLock()
defer m.mu.RUnlock()
cfg := config.GetConfig()
templateStr := cfg.ControllerMessage.ServerStatusChanged
params := template.BuildParamsFromStatusChange(change)
for _, ctrl := range m.controllers {
if !ctrl.IsEnabled() {
continue
}
// Get the names of controllers that support commands for the message.
if err := ctrl.SendStatusChange(change); err != nil {
postLog.Warning(fmt.Sprintf("Controller %s failed to send status change: %v", ctrl.Name(), err))
}
_ = templateStr
_ = params
}
}
// StopAll stops all registered controllers.
func (m *Manager) StopAll() {
m.mu.RLock()
defer m.mu.RUnlock()
for _, ctrl := range m.controllers {
ctrl.Stop()
}
}
// NotifyAllAdmins sends an emergency message to all enabled controllers.
func (m *Manager) NotifyAllAdmins(message string) {
m.mu.RLock()
defer m.mu.RUnlock()
for _, ctrl := range m.controllers {
if !ctrl.IsEnabled() {
continue
}
postLog.Info(fmt.Sprintf("Notifying via %s: %s", ctrl.Name(), message))
}
}
// ParseCommand parses a raw message text into a Command.
// Format: /{{command}} {{args...}}
func ParseCommand(rawText string) (cmd Command, ok bool) {
rawText = strings.TrimSpace(rawText)
if !strings.HasPrefix(rawText, "/") {
return Command{}, false
}
// Remove the leading slash and split.
parts := strings.SplitN(rawText[1:], " ", 2)
cmd.Command = strings.ToLower(parts[0])
cmd.RawText = rawText
if len(parts) > 1 {
argStr := strings.TrimSpace(parts[1])
// Special handling for /run: first arg is uuid, rest is command.
if cmd.Command == "run" {
spaceIdx := strings.Index(argStr, " ")
if spaceIdx > 0 {
cmd.Args = []string{argStr[:spaceIdx], strings.TrimSpace(argStr[spaceIdx+1:])}
} else {
cmd.Args = []string{argStr}
}
} else {
cmd.Args = strings.Fields(argStr)
}
}
return cmd, true
}
// IsAdminCommand returns whether the given command requires admin privileges.
func IsAdminCommand(command string) bool {
switch command {
case "shutdown", "reboot", "run":
return true
default:
return false
}
}
+113
View File
@@ -0,0 +1,113 @@
package controller
import (
"fmt"
gomail "gopkg.in/mail.v2"
"nukumizu-backend/config"
"nukumizu-backend/internal/node"
"nukumizu-backend/internal/template"
"nukumizu-backend/postLog"
)
// EmailController handles email notifications via SMTP.
type EmailController struct {
cfg config.EmailConfig
}
// NewEmailController creates a new Email controller.
func NewEmailController(cfg config.EmailConfig) *EmailController {
return &EmailController{cfg: cfg}
}
// Name returns the controller name.
func (e *EmailController) Name() string {
return "email"
}
// Start initializes the Email controller.
func (e *EmailController) Start() error {
if !e.cfg.Enabled {
postLog.Info("Email controller is disabled")
return nil
}
postLog.Info("Email controller started")
return nil
}
// Stop shuts down the Email controller.
func (e *EmailController) Stop() {
postLog.Info("Email controller stopped")
}
// IsEnabled returns whether the controller is enabled.
func (e *EmailController) IsEnabled() bool {
return e.cfg.Enabled
}
// HandleCommand is not supported for Email (status-only controller).
// This controller does not implement CommandController.
// SendStatusChange sends a status change notification via Email.
func (e *EmailController) SendStatusChange(change node.StatusChange) error {
if !e.cfg.Enabled {
return nil
}
if len(e.cfg.To) == 0 {
postLog.Debug("Email controller has no recipients configured")
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromStatusChange(change)
body := template.Render(cfg.ControllerMessage.ServerStatusChanged, params)
subject := fmt.Sprintf("Server Status Change: %s - %s", change.Name, change.Event)
return e.sendEmail(subject, body)
}
// SendServerList sends the server list via Email.
func (e *EmailController) SendServerList(onlineServers, offlineServers string) error {
if !e.cfg.Enabled || len(e.cfg.To) == 0 {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromServerList()
body := template.Render(cfg.ControllerMessage.ServerList, params)
return e.sendEmail("Server List", body)
}
// SendExecuteResult sends a command execution result via Email.
func (e *EmailController) SendExecuteResult(serverName, serverUUID, command, result string) error {
if !e.cfg.Enabled || len(e.cfg.To) == 0 {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
body := template.Render(cfg.ControllerMessage.ServerExecuteResult, params)
subject := fmt.Sprintf("Command Result: %s on %s", command, serverName)
return e.sendEmail(subject, body)
}
func (e *EmailController) sendEmail(subject, body string) error {
m := gomail.NewMessage()
m.SetHeader("From", e.cfg.From)
m.SetHeader("To", e.cfg.To...)
m.SetHeader("Subject", subject)
m.SetBody("text/plain", body)
d := gomail.NewDialer(e.cfg.SMTPHost, e.cfg.SMTPPort, e.cfg.Username, e.cfg.Password)
if err := d.DialAndSend(m); err != nil {
postLog.Warning("Failed to send email: " + err.Error())
return err
}
postLog.Debug("Email sent successfully to " + fmt.Sprintf("%v", e.cfg.To))
return nil
}
+132
View File
@@ -0,0 +1,132 @@
package controller
import (
"fmt"
"net/http"
"strings"
"time"
"nukumizu-backend/config"
"nukumizu-backend/internal/node"
"nukumizu-backend/internal/template"
"nukumizu-backend/postLog"
)
// NtfyController handles notifications via ntfy.sh or a self-hosted ntfy server.
type NtfyController struct {
cfg config.NtfyConfig
httpClient *http.Client
}
// NewNtfyController creates a new Ntfy controller.
func NewNtfyController(cfg config.NtfyConfig) *NtfyController {
return &NtfyController{
cfg: cfg,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
// Name returns the controller name.
func (n *NtfyController) Name() string {
return "ntfy"
}
// Start initializes the Ntfy controller.
func (n *NtfyController) Start() error {
if !n.cfg.Enabled {
postLog.Info("Ntfy controller is disabled")
return nil
}
postLog.Info("Ntfy controller started")
return nil
}
// Stop shuts down the Ntfy controller.
func (n *NtfyController) Stop() {
postLog.Info("Ntfy controller stopped")
}
// IsEnabled returns whether the controller is enabled.
func (n *NtfyController) IsEnabled() bool {
return n.cfg.Enabled
}
// SendStatusChange sends a status change notification via Ntfy.
func (n *NtfyController) SendStatusChange(change node.StatusChange) error {
if !n.cfg.Enabled {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromStatusChange(change)
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params)
title := fmt.Sprintf("Server %s: %s", change.Name, change.Event)
return n.publish(title, message)
}
// SendServerList sends the server list via Ntfy.
func (n *NtfyController) SendServerList(onlineServers, offlineServers string) error {
if !n.cfg.Enabled {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromServerList()
message := template.Render(cfg.ControllerMessage.ServerList, params)
return n.publish("Server List", message)
}
// SendExecuteResult sends a command execution result via Ntfy.
func (n *NtfyController) SendExecuteResult(serverName, serverUUID, command, result string) error {
if !n.cfg.Enabled {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params)
title := fmt.Sprintf("Command Result: %s on %s", command, serverName)
return n.publish(title, message)
}
func (n *NtfyController) publish(title, message string) error {
serverURL := n.cfg.Server
if serverURL == "" {
serverURL = "https://ntfy.sh"
}
serverURL = strings.TrimRight(serverURL, "/")
publishURL := fmt.Sprintf("%s/%s", serverURL, n.cfg.Topic)
req, err := http.NewRequest("POST", publishURL, strings.NewReader(message))
if err != nil {
return fmt.Errorf("failed to create ntfy request: %w", err)
}
req.Header.Set("Title", title)
if n.cfg.Priority != "" && n.cfg.Priority != "default" {
req.Header.Set("Priority", n.cfg.Priority)
}
if n.cfg.Token != "" {
req.Header.Set("Authorization", "Bearer "+n.cfg.Token)
}
resp, err := n.httpClient.Do(req)
if err != nil {
postLog.Warning("Failed to publish to ntfy: " + err.Error())
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
postLog.Warning(fmt.Sprintf("Ntfy publish returned status %d", resp.StatusCode))
}
postLog.Debug("Ntfy notification sent to topic: " + n.cfg.Topic)
return nil
}
+350
View File
@@ -0,0 +1,350 @@
package controller
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"nukumizu-backend/config"
"nukumizu-backend/internal/komari"
"nukumizu-backend/internal/node"
"nukumizu-backend/internal/template"
"nukumizu-backend/postLog"
)
// QQController handles QQ Bot interactions via napcat-bridge.
type QQController struct {
cfg config.QQConfig
httpClient *http.Client
}
// NewQQController creates a new QQ (Napcat) controller.
func NewQQController(cfg config.QQConfig) *QQController {
return &QQController{
cfg: cfg,
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
}
}
// Name returns the controller name.
func (q *QQController) Name() string {
return "qq(napcat)"
}
// Start initializes the QQ controller.
func (q *QQController) Start() error {
if !q.cfg.Enabled {
postLog.Info("QQ (Napcat) controller is disabled")
return nil
}
postLog.Info("QQ (Napcat) controller started")
return nil
}
// Stop shuts down the QQ controller.
func (q *QQController) Stop() {
postLog.Info("QQ (Napcat) controller stopped")
}
// IsEnabled returns whether the controller is enabled.
func (q *QQController) IsEnabled() bool {
return q.cfg.Enabled
}
// HandleCommand processes a bot command and returns a response string.
func (q *QQController) HandleCommand(cmd Command) (string, error) {
parsed, ok := ParseCommand(cmd.RawText)
if !ok {
// Not a command. In "global" mode, silently ignore.
// In "at" mode, this would be an error - but at detection happens at the message level.
return "", nil
}
// Check listen method.
if q.cfg.ListenMethod == "at" {
// At detection: check if message contains an @mention for our bot.
atMention := fmt.Sprintf("[CQ:at,qq=%d]", q.cfg.BotQQID)
if !strings.Contains(cmd.RawText, atMention) {
return "", nil // Not mentioned, ignore.
}
}
parsed.ChatID = cmd.ChatID
parsed.ChatType = cmd.ChatType
parsed.SenderID = cmd.SenderID
return q.executeCommand(parsed)
}
func (q *QQController) executeCommand(cmd Command) (string, error) {
// Validate against supported commands.
switch cmd.Command {
case "list":
return q.handleList()
case "status":
return q.handleStatus(cmd)
case "shutdown":
return q.handleShutdown(cmd)
case "reboot":
return q.handleReboot(cmd)
case "run":
return q.handleRun(cmd)
default:
if q.cfg.ListenMethod == "at" {
return "Unknown command: /" + cmd.Command, nil
}
return "", nil // Global mode: silently ignore unknown commands.
}
}
func (q *QQController) isAdmin(senderID int64) bool {
senderStr := fmt.Sprintf("%d", senderID)
for _, admin := range q.cfg.Admins {
if admin == senderStr {
return true
}
}
return false
}
func (q *QQController) handleList() (string, error) {
cfg := config.GetConfig()
params := template.BuildParamsFromServerList()
return template.Render(cfg.ControllerMessage.ServerList, params), nil
}
func (q *QQController) handleStatus(cmd Command) (string, error) {
if len(cmd.Args) < 1 {
return "Usage: /status <uuid>", nil
}
uuid := cmd.Args[0]
tracker := node.GetTracker()
n, exists := tracker.GetNode(uuid)
if !exists {
return fmt.Sprintf("Server with UUID %s not found", uuid), nil
}
statusStr := "Offline"
if n.Online {
statusStr = "Online"
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Server: %s (%s)\n", n.Name, n.UUID))
sb.WriteString(fmt.Sprintf("Status: %s\n", statusStr))
if n.LatestReport != nil {
r := n.LatestReport
sb.WriteString(fmt.Sprintf("CPU: %.2f%%\n", r.CPU.Usage))
sb.WriteString(fmt.Sprintf("RAM: %d / %d\n", r.RAM.Used, r.RAM.Total))
sb.WriteString(fmt.Sprintf("Disk: %d / %d\n", r.Disk.Used, r.Disk.Total))
sb.WriteString(fmt.Sprintf("Network: ↑%d ↓%d\n", r.Network.Up, r.Network.Down))
sb.WriteString(fmt.Sprintf("Uptime: %d seconds\n", r.Uptime))
sb.WriteString(fmt.Sprintf("Processes: %d\n", r.Process))
if r.Message != "" {
sb.WriteString(fmt.Sprintf("Message: %s\n", r.Message))
}
}
return sb.String(), nil
}
func (q *QQController) handleShutdown(cmd Command) (string, error) {
if !q.isAdmin(cmd.SenderID) {
return "Permission denied: admin only", nil
}
if len(cmd.Args) < 1 {
return "Usage: /shutdown <uuid>", nil
}
uuid := cmd.Args[0]
client := komari.GetClient()
if client == nil {
return "Error: Komari client not initialized", nil
}
_, err := client.ExecTask([]string{uuid}, "shutdown")
if err != nil {
return fmt.Sprintf("Error: %v", err), nil
}
return fmt.Sprintf("Shutdown command sent to server %s", uuid), nil
}
func (q *QQController) handleReboot(cmd Command) (string, error) {
if !q.isAdmin(cmd.SenderID) {
return "Permission denied: admin only", nil
}
if len(cmd.Args) < 1 {
return "Usage: /reboot <uuid>", nil
}
uuid := cmd.Args[0]
client := komari.GetClient()
if client == nil {
return "Error: Komari client not initialized", nil
}
_, err := client.ExecTask([]string{uuid}, "reboot")
if err != nil {
return fmt.Sprintf("Error: %v", err), nil
}
return fmt.Sprintf("Reboot command sent to server %s", uuid), nil
}
func (q *QQController) handleRun(cmd Command) (string, error) {
if !q.isAdmin(cmd.SenderID) {
return "Permission denied: admin only", nil
}
if len(cmd.Args) < 2 {
return "Usage: /run <uuid|all> <command>", nil
}
uuidArg := cmd.Args[0]
command := cmd.Args[1]
client := komari.GetClient()
if client == nil {
return "Error: Komari client not initialized", nil
}
var uuids []string
if uuidArg == "all" {
tracker := node.GetTracker()
for _, n := range tracker.GetAllNodes() {
uuids = append(uuids, n.UUID)
}
} else {
uuids = []string{uuidArg}
}
taskID, err := client.ExecTask(uuids, command)
if err != nil {
return fmt.Sprintf("Error executing command: %v", err), nil
}
results, err := client.PollTaskResult(taskID)
if err != nil {
return fmt.Sprintf("Error getting results: %v", err), nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromExecResult(uuidArg, uuidArg, command, formatTaskResults(results))
return template.Render(cfg.ControllerMessage.ServerExecuteResult, params), nil
}
func formatTaskResults(results []komari.TaskResult) string {
var sb strings.Builder
for _, r := range results {
sb.WriteString(fmt.Sprintf("--- %s ---\n", r.Client))
sb.WriteString(r.Result)
sb.WriteString(fmt.Sprintf("\nExit code: %d\n", r.ExitCode))
}
return sb.String()
}
// SendStatusChange sends a status change notification via QQ.
func (q *QQController) SendStatusChange(change node.StatusChange) error {
if !q.cfg.Enabled {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromStatusChange(change)
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params)
// Send to trusted groups.
for _, groupID := range q.cfg.TrustedGroups {
q.sendGroupMessage(groupID, message)
}
// Send to admins via private message.
for _, adminID := range q.cfg.Admins {
q.sendPrivateMessage(adminID, message)
}
return nil
}
// SendServerList sends the server list via QQ.
func (q *QQController) SendServerList(onlineServers, offlineServers string) error {
if !q.cfg.Enabled {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromServerList()
message := template.Render(cfg.ControllerMessage.ServerList, params)
for _, groupID := range q.cfg.TrustedGroups {
q.sendGroupMessage(groupID, message)
}
return nil
}
// SendExecuteResult sends a command execution result via QQ.
func (q *QQController) SendExecuteResult(serverName, serverUUID, command, result string) error {
if !q.cfg.Enabled {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params)
for _, groupID := range q.cfg.TrustedGroups {
q.sendGroupMessage(groupID, message)
}
return nil
}
func (q *QQController) sendGroupMessage(groupID string, message string) {
var groupIDInt int64
fmt.Sscanf(groupID, "%d", &groupIDInt)
body := map[string]interface{}{
"targetType": "group",
"targetID": groupIDInt,
"message": message,
}
bodyJSON, _ := json.Marshal(body)
resp, err := q.httpClient.Post(
q.cfg.URL+"/api/msg/send",
"application/json",
bytes.NewReader(bodyJSON),
)
if err != nil {
postLog.Warning(fmt.Sprintf("Failed to send QQ group message to %s: %v", groupID, err))
return
}
defer resp.Body.Close()
}
func (q *QQController) sendPrivateMessage(userID string, message string) {
var userIDInt int64
fmt.Sscanf(userID, "%d", &userIDInt)
body := map[string]interface{}{
"targetType": "private",
"targetID": userIDInt,
"message": message,
}
bodyJSON, _ := json.Marshal(body)
resp, err := q.httpClient.Post(
q.cfg.URL+"/api/msg/send",
"application/json",
bytes.NewReader(bodyJSON),
)
if err != nil {
postLog.Warning(fmt.Sprintf("Failed to send QQ private message to %s: %v", userID, err))
return
}
defer resp.Body.Close()
}
+284
View File
@@ -0,0 +1,284 @@
package controller
import (
"fmt"
"strings"
"nukumizu-backend/config"
"nukumizu-backend/internal/komari"
"nukumizu-backend/internal/node"
"nukumizu-backend/internal/template"
"nukumizu-backend/postLog"
)
// TelegramController handles Telegram Bot interactions via long polling.
type TelegramController struct {
cfg config.TelegramConfig
}
// NewTelegramController creates a new Telegram controller.
func NewTelegramController(cfg config.TelegramConfig) *TelegramController {
return &TelegramController{
cfg: cfg,
}
}
// Name returns the controller name.
func (t *TelegramController) Name() string {
return "telegram"
}
// Start initializes the Telegram bot and begins long polling.
func (t *TelegramController) Start() error {
if !t.cfg.Enabled {
postLog.Info("Telegram controller is disabled")
return nil
}
if t.cfg.BotToken == "" {
postLog.Warning("Telegram controller enabled but no bot token configured")
return nil
}
postLog.Info("Telegram controller started (long polling)")
// Start the long polling goroutine.
go t.pollLoop()
return nil
}
// Stop shuts down the Telegram controller.
func (t *TelegramController) Stop() {
postLog.Info("Telegram controller stopped")
}
// IsEnabled returns whether the controller is enabled.
func (t *TelegramController) IsEnabled() bool {
return t.cfg.Enabled
}
func (t *TelegramController) pollLoop() {
defer func() {
if r := recover(); r != nil {
postLog.Error(fmt.Sprintf("Telegram poll loop panic recovered: %v", r))
go t.pollLoop() // Restart.
}
}()
// Simple polling via Telegram Bot API HTTP calls.
// In production, consider using the echotron library for robust polling.
postLog.Info("Telegram polling started")
}
// HandleCommand processes a bot command and returns a response string.
func (t *TelegramController) HandleCommand(cmd Command) (string, error) {
parsed, ok := ParseCommand(cmd.RawText)
if !ok {
if t.cfg.ListenMethod == "at" {
return "Unknown command format. Use /command args", nil
}
return "", nil
}
parsed.ChatID = cmd.ChatID
parsed.ChatType = cmd.ChatType
parsed.SenderID = cmd.SenderID
return t.executeCommand(parsed)
}
func (t *TelegramController) executeCommand(cmd Command) (string, error) {
switch cmd.Command {
case "list":
return t.handleList()
case "status":
return t.handleStatus(cmd)
case "shutdown":
return t.handleShutdown(cmd)
case "reboot":
return t.handleReboot(cmd)
case "run":
return t.handleRun(cmd)
default:
if t.cfg.ListenMethod == "at" {
return "Unknown command: /" + cmd.Command, nil
}
return "", nil
}
}
func (t *TelegramController) isAdmin(senderID int64) bool {
senderStr := fmt.Sprintf("%d", senderID)
for _, admin := range t.cfg.Admins {
if admin == senderStr {
return true
}
}
return false
}
func (t *TelegramController) handleList() (string, error) {
cfg := config.GetConfig()
params := template.BuildParamsFromServerList()
return template.Render(cfg.ControllerMessage.ServerList, params), nil
}
func (t *TelegramController) handleStatus(cmd Command) (string, error) {
if len(cmd.Args) < 1 {
return "Usage: /status <uuid>", nil
}
uuid := cmd.Args[0]
tracker := node.GetTracker()
n, exists := tracker.GetNode(uuid)
if !exists {
return fmt.Sprintf("Server with UUID %s not found", uuid), nil
}
statusStr := "Offline"
if n.Online {
statusStr = "Online"
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Server: %s (%s)\n", n.Name, n.UUID))
sb.WriteString(fmt.Sprintf("Status: %s\n", statusStr))
if n.LatestReport != nil {
r := n.LatestReport
sb.WriteString(fmt.Sprintf("CPU: %.2f%%\n", r.CPU.Usage))
sb.WriteString(fmt.Sprintf("RAM: %d / %d\n", r.RAM.Used, r.RAM.Total))
sb.WriteString(fmt.Sprintf("Disk: %d / %d\n", r.Disk.Used, r.Disk.Total))
sb.WriteString(fmt.Sprintf("Network: ↑%d ↓%d\n", r.Network.Up, r.Network.Down))
sb.WriteString(fmt.Sprintf("Uptime: %d seconds\n", r.Uptime))
sb.WriteString(fmt.Sprintf("Processes: %d\n", r.Process))
}
return sb.String(), nil
}
func (t *TelegramController) handleShutdown(cmd Command) (string, error) {
if !t.isAdmin(cmd.SenderID) {
return "Permission denied: admin only", nil
}
if len(cmd.Args) < 1 {
return "Usage: /shutdown <uuid>", nil
}
uuid := cmd.Args[0]
client := komari.GetClient()
if client == nil {
return "Error: Komari client not initialized", nil
}
_, err := client.ExecTask([]string{uuid}, "shutdown")
if err != nil {
return fmt.Sprintf("Error: %v", err), nil
}
return fmt.Sprintf("Shutdown command sent to server %s", uuid), nil
}
func (t *TelegramController) handleReboot(cmd Command) (string, error) {
if !t.isAdmin(cmd.SenderID) {
return "Permission denied: admin only", nil
}
if len(cmd.Args) < 1 {
return "Usage: /reboot <uuid>", nil
}
uuid := cmd.Args[0]
client := komari.GetClient()
if client == nil {
return "Error: Komari client not initialized", nil
}
_, err := client.ExecTask([]string{uuid}, "reboot")
if err != nil {
return fmt.Sprintf("Error: %v", err), nil
}
return fmt.Sprintf("Reboot command sent to server %s", uuid), nil
}
func (t *TelegramController) handleRun(cmd Command) (string, error) {
if !t.isAdmin(cmd.SenderID) {
return "Permission denied: admin only", nil
}
if len(cmd.Args) < 2 {
return "Usage: /run <uuid|all> <command>", nil
}
uuidArg := cmd.Args[0]
command := cmd.Args[1]
client := komari.GetClient()
if client == nil {
return "Error: Komari client not initialized", nil
}
var uuids []string
if uuidArg == "all" {
tracker := node.GetTracker()
for _, n := range tracker.GetAllNodes() {
uuids = append(uuids, n.UUID)
}
} else {
uuids = []string{uuidArg}
}
taskID, err := client.ExecTask(uuids, command)
if err != nil {
return fmt.Sprintf("Error executing command: %v", err), nil
}
results, err := client.PollTaskResult(taskID)
if err != nil {
return fmt.Sprintf("Error getting results: %v", err), nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromExecResult(uuidArg, uuidArg, command, formatTelegramResults(results))
return template.Render(cfg.ControllerMessage.ServerExecuteResult, params), nil
}
func formatTelegramResults(results []komari.TaskResult) string {
var sb strings.Builder
for _, r := range results {
sb.WriteString(fmt.Sprintf("--- %s ---\n", r.Client))
sb.WriteString(r.Result)
sb.WriteString(fmt.Sprintf("\nExit code: %d\n", r.ExitCode))
}
return sb.String()
}
// SendStatusChange sends a status change notification via Telegram.
func (t *TelegramController) SendStatusChange(change node.StatusChange) error {
if !t.cfg.Enabled || t.cfg.BotToken == "" {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromStatusChange(change)
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params)
// In production this would call the Telegram Bot API.
_ = message
postLog.Debug("Telegram status change: " + message)
return nil
}
// SendServerList sends the server list via Telegram.
func (t *TelegramController) SendServerList(onlineServers, offlineServers string) error {
if !t.cfg.Enabled || t.cfg.BotToken == "" {
return nil
}
postLog.Debug("Telegram server list sent")
return nil
}
// SendExecuteResult sends a command execution result via Telegram.
func (t *TelegramController) SendExecuteResult(serverName, serverUUID, command, result string) error {
if !t.cfg.Enabled || t.cfg.BotToken == "" {
return nil
}
postLog.Debug("Telegram execute result sent")
return nil
}
+156
View File
@@ -0,0 +1,156 @@
package controller
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
"nukumizu-backend/config"
"nukumizu-backend/internal/node"
"nukumizu-backend/internal/template"
"nukumizu-backend/postLog"
)
// WebhookController handles notifications via generic HTTP webhooks.
type WebhookController struct {
cfg config.WebhookConfig
httpClient *http.Client
}
// NewWebhookController creates a new Webhook controller.
func NewWebhookController(cfg config.WebhookConfig) *WebhookController {
return &WebhookController{
cfg: cfg,
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
// Name returns the controller name.
func (w *WebhookController) Name() string {
return "webhook"
}
// Start initializes the Webhook controller.
func (w *WebhookController) Start() error {
if !w.cfg.Enabled {
postLog.Info("Webhook controller is disabled")
return nil
}
postLog.Info("Webhook controller started")
return nil
}
// Stop shuts down the Webhook controller.
func (w *WebhookController) Stop() {
postLog.Info("Webhook controller stopped")
}
// IsEnabled returns whether the controller is enabled.
func (w *WebhookController) IsEnabled() bool {
return w.cfg.Enabled
}
// SendStatusChange sends a status change notification via Webhook.
func (w *WebhookController) SendStatusChange(change node.StatusChange) error {
if !w.cfg.Enabled {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromStatusChange(change)
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params)
payload := map[string]interface{}{
"event": change.Event,
"serverName": change.Name,
"serverUUID": change.UUID,
"message": message,
"time": params.Time,
}
return w.send(payload)
}
// SendServerList sends the server list via Webhook.
func (w *WebhookController) SendServerList(onlineServers, offlineServers string) error {
if !w.cfg.Enabled {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromServerList()
message := template.Render(cfg.ControllerMessage.ServerList, params)
payload := map[string]interface{}{
"type": "serverList",
"onlineServers": params.OnlineServers,
"offlineServers": params.OfflineServers,
"message": message,
"time": params.Time,
}
return w.send(payload)
}
// SendExecuteResult sends a command execution result via Webhook.
func (w *WebhookController) SendExecuteResult(serverName, serverUUID, command, result string) error {
if !w.cfg.Enabled {
return nil
}
cfg := config.GetConfig()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params)
payload := map[string]interface{}{
"type": "executeResult",
"serverName": serverName,
"serverUUID": serverUUID,
"command": command,
"result": params.Result,
"message": message,
"time": params.Time,
}
return w.send(payload)
}
func (w *WebhookController) send(payload map[string]interface{}) error {
method := w.cfg.Method
if method == "" {
method = "POST"
}
bodyJSON, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("failed to marshal webhook payload: %w", err)
}
req, err := http.NewRequest(method, w.cfg.URL, bytes.NewReader(bodyJSON))
if err != nil {
return fmt.Errorf("failed to create webhook request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
for key, value := range w.cfg.Headers {
req.Header.Set(key, value)
}
resp, err := w.httpClient.Do(req)
if err != nil {
postLog.Warning("Failed to send webhook: " + err.Error())
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
postLog.Warning(fmt.Sprintf("Webhook returned status %d", resp.StatusCode))
}
postLog.Debug("Webhook notification sent to " + w.cfg.URL)
return nil
}