| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423 |
- package api
- import (
- "encoding/json"
- "net/http"
- "strconv"
- "strings"
- "sync"
- "time"
- "github.com/gorilla/websocket"
- "AI-Status-Light/internal/database"
- "AI-Status-Light/internal/logger"
- )
- type Server struct {
- db *database.DB
- server *http.Server
- clients map[*websocket.Conn]bool
- clientsMu sync.Mutex
- upgrader websocket.Upgrader
- }
- type Response struct {
- Code int `json:"code"`
- Message string `json:"message"`
- Data interface{} `json:"data,omitempty"`
- }
- func New(db *database.DB, addr string) *Server {
- s := &Server{
- db: db,
- clients: make(map[*websocket.Conn]bool),
- upgrader: websocket.Upgrader{
- CheckOrigin: func(r *http.Request) bool {
- return true
- },
- },
- }
- mux := http.NewServeMux()
- mux.HandleFunc("/api/mqtt", s.handleMQTT)
- mux.HandleFunc("/api/mqtt/", s.handleMQTTByID)
- mux.HandleFunc("/api/health", s.handleHealth)
- mux.HandleFunc("/ws", s.handleWebSocket)
- mux.HandleFunc("/", s.handleIndex)
- s.server = &http.Server{
- Addr: addr,
- Handler: corsMiddleware(mux),
- }
- return s
- }
- func (s *Server) Start() error {
- logger.Info("API 服务器开始监听: %s", s.server.Addr)
- err := s.server.ListenAndServe()
- if err != nil && err != http.ErrServerClosed {
- logger.Error("API 服务器监听失败: %v", err)
- }
- return err
- }
- func corsMiddleware(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Access-Control-Allow-Origin", "*")
- w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
- w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
- if r.Method == "OPTIONS" {
- w.WriteHeader(http.StatusOK)
- return
- }
- next.ServeHTTP(w, r)
- })
- }
- func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
- writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok"})
- }
- func (s *Server) handleMQTT(w http.ResponseWriter, r *http.Request) {
- logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
- switch r.Method {
- case http.MethodGet:
- s.listMQTTConfigs(w, r)
- case http.MethodPost:
- s.createMQTTConfig(w, r)
- default:
- logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
- writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
- }
- }
- func (s *Server) handleMQTTByID(w http.ResponseWriter, r *http.Request) {
- logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
- idStr := strings.TrimPrefix(r.URL.Path, "/api/mqtt/")
- id, err := strconv.Atoi(idStr)
- if err != nil {
- logger.Warn("无效的配置 ID: %s", idStr)
- writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的 ID"})
- return
- }
- switch r.Method {
- case http.MethodGet:
- s.getMQTTConfig(w, id)
- case http.MethodPut:
- s.updateMQTTConfig(w, r, id)
- case http.MethodDelete:
- s.deleteMQTTConfig(w, id)
- default:
- logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
- writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
- }
- }
- func (s *Server) listMQTTConfigs(w http.ResponseWriter, r *http.Request) {
- configs, err := s.db.ListMQTTConfigs()
- if err != nil {
- logger.Error("查询 MQTT 配置列表失败: %v", err)
- writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
- return
- }
- logger.Debug("查询 MQTT 配置列表: %d 条", len(configs))
- writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: configs})
- }
- func (s *Server) createMQTTConfig(w http.ResponseWriter, r *http.Request) {
- var cfg database.MQTTConfig
- if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
- logger.Warn("创建配置请求体解析失败: %v", err)
- writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
- return
- }
- if cfg.Broker == "" {
- logger.Warn("创建配置: broker 为空")
- writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "broker 不能为空"})
- return
- }
- if cfg.ClientID == "" {
- cfg.ClientID = "opencode-monitor"
- }
- if cfg.Topic == "" {
- cfg.Topic = "opencode/status"
- }
- if err := s.db.SaveMQTTConfig(&cfg); err != nil {
- logger.Error("创建 MQTT 配置失败: %v", err)
- writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
- return
- }
- logger.Info("MQTT 配置已创建: id=%d, broker=%s, topic=%s", cfg.ID, cfg.Broker, cfg.Topic)
- writeJSON(w, http.StatusCreated, Response{Code: 0, Message: "创建成功", Data: cfg})
- }
- func (s *Server) getMQTTConfig(w http.ResponseWriter, id int) {
- configs, err := s.db.ListMQTTConfigs()
- if err != nil {
- logger.Error("查询 MQTT 配置失败: id=%d, %v", id, err)
- writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
- return
- }
- for _, cfg := range configs {
- if cfg.ID == id {
- logger.Debug("查询 MQTT 配置: id=%d", id)
- writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: cfg})
- return
- }
- }
- logger.Warn("MQTT 配置不存在: id=%d", id)
- writeJSON(w, http.StatusNotFound, Response{Code: -1, Message: "配置不存在"})
- }
- func (s *Server) updateMQTTConfig(w http.ResponseWriter, r *http.Request, id int) {
- var cfg database.MQTTConfig
- if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
- logger.Warn("更新配置请求体解析失败: id=%d, %v", id, err)
- writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
- return
- }
- cfg.ID = id
- if cfg.Broker == "" {
- logger.Warn("更新配置: broker 为空, id=%d", id)
- writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "broker 不能为空"})
- return
- }
- if cfg.ClientID == "" {
- cfg.ClientID = "opencode-monitor"
- }
- if cfg.Topic == "" {
- cfg.Topic = "opencode/status"
- }
- if err := s.db.SaveMQTTConfig(&cfg); err != nil {
- logger.Error("更新 MQTT 配置失败: id=%d, %v", id, err)
- writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
- return
- }
- logger.Info("MQTT 配置已更新: id=%d, broker=%s, topic=%s", id, cfg.Broker, cfg.Topic)
- writeJSON(w, http.StatusOK, Response{Code: 0, Message: "更新成功", Data: cfg})
- }
- func (s *Server) deleteMQTTConfig(w http.ResponseWriter, id int) {
- if err := s.db.DeleteMQTTConfig(id); err != nil {
- logger.Error("删除 MQTT 配置失败: id=%d, %v", id, err)
- writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
- return
- }
- logger.Info("MQTT 配置已删除: id=%d", id)
- writeJSON(w, http.StatusOK, Response{Code: 0, Message: "删除成功"})
- }
- func writeJSON(w http.ResponseWriter, statusCode int, data interface{}) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(statusCode)
- json.NewEncoder(w).Encode(data)
- }
- func (s *Server) GetAddr() string {
- return s.server.Addr
- }
- func (s *Server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
- conn, err := s.upgrader.Upgrade(w, r, nil)
- if err != nil {
- logger.Error("WebSocket 升级失败: %v", err)
- return
- }
- s.clientsMu.Lock()
- s.clients[conn] = true
- s.clientsMu.Unlock()
- logger.Info("WebSocket 客户端已连接,当前连接数: %d", len(s.clients))
- go func() {
- defer func() {
- s.clientsMu.Lock()
- delete(s.clients, conn)
- s.clientsMu.Unlock()
- conn.Close()
- logger.Info("WebSocket 客户端已断开,当前连接数: %d", len(s.clients))
- }()
- for {
- _, _, err := conn.ReadMessage()
- if err != nil {
- break
- }
- }
- }()
- }
- func (s *Server) BroadcastStatus(port int, status string, code string) {
- s.clientsMu.Lock()
- defer s.clientsMu.Unlock()
- if len(s.clients) == 0 {
- return
- }
- payload := map[string]interface{}{
- "port": port,
- "status": status,
- "code": code,
- "timestamp": time.Now().Format(time.RFC3339),
- }
- data, err := json.Marshal(payload)
- if err != nil {
- logger.Error("序列化广播消息失败: %v", err)
- return
- }
- for client := range s.clients {
- err := client.WriteMessage(websocket.TextMessage, data)
- if err != nil {
- logger.Debug("WebSocket 写入失败,移除客户端: %v", err)
- client.Close()
- delete(s.clients, client)
- }
- }
- }
- func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/" {
- http.NotFound(w, r)
- return
- }
- html := `<!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>OpenCode Monitor</title>
- <style>
- * { margin: 0; padding: 0; box-sizing: border-box; }
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }
- .container { max-width: 1200px; margin: 0 auto; }
- h1 { color: #333; margin-bottom: 20px; }
- .status-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }
- .status-card { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
- .status-card h2 { color: #666; font-size: 14px; margin-bottom: 8px; }
- .status-value { font-size: 32px; font-weight: bold; margin-bottom: 8px; }
- .status-time { color: #999; font-size: 12px; }
- .status-空闲 { color: #52c41a; }
- .status-工作中 { color: #ff4d4f; }
- .status-思考中 { color: #faad14; }
- .status-运行中 { color: #1890ff; }
- .status-完成 { color: #52c41a; }
- .status-错误 { color: #ff4d4f; }
- .status-重试中 { color: #faad14; }
- .status-修改中 { color: #722ed1; }
- .log { margin-top: 20px; background: white; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
- .log h2 { color: #666; font-size: 14px; margin-bottom: 12px; }
- .log-list { max-height: 300px; overflow-y: auto; }
- .log-item { padding: 8px 0; border-bottom: 1px solid #f0f0f0; font-size: 14px; }
- .log-item:last-child { border-bottom: none; }
- .log-time { color: #999; margin-right: 8px; }
- .log-port { color: #1890ff; margin-right: 8px; }
- .connected { color: #52c41a; font-size: 12px; margin-left: 10px; }
- .disconnected { color: #ff4d4f; font-size: 12px; margin-left: 10px; }
- </style>
- </head>
- <body>
- <div class="container">
- <h1>OpenCode Monitor <span id="connectionStatus" class="disconnected">● 未连接</span></h1>
- <div class="status-grid" id="statusGrid">
- <div class="status-card">
- <h2>当前状态</h2>
- <div class="status-value" id="currentStatus">等待中...</div>
- <div class="status-time" id="statusTime"></div>
- </div>
- </div>
- <div class="log">
- <h2>状态日志</h2>
- <div class="log-list" id="logList"></div>
- </div>
- </div>
- <script>
- const statusGrid = document.getElementById('statusGrid');
- const logList = document.getElementById('logList');
- const currentStatus = document.getElementById('currentStatus');
- const statusTime = document.getElementById('statusTime');
- const connectionStatus = document.getElementById('connectionStatus');
-
- let ws = null;
- let reconnectTimer = null;
- function connect() {
- const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
- ws = new WebSocket(protocol + '//' + window.location.host + '/ws');
- ws.onopen = function() {
- connectionStatus.textContent = '● 已连接';
- connectionStatus.className = 'connected';
- if (reconnectTimer) {
- clearTimeout(reconnectTimer);
- reconnectTimer = null;
- }
- };
- ws.onmessage = function(event) {
- try {
- const data = JSON.parse(event.data);
- updateStatus(data);
- addLog(data);
- } catch (e) {
- console.error('解析消息失败:', e);
- }
- };
- ws.onclose = function() {
- connectionStatus.textContent = '● 未连接';
- connectionStatus.className = 'disconnected';
- reconnectTimer = setTimeout(connect, 3000);
- };
- ws.onerror = function() {
- ws.close();
- };
- }
- function updateStatus(data) {
- currentStatus.textContent = data.status;
- currentStatus.className = 'status-value status-' + data.status;
- statusTime.textContent = '端口: ' + data.port + ' | 更新时间: ' + new Date().toLocaleTimeString();
- }
- function addLog(data) {
- const item = document.createElement('div');
- item.className = 'log-item';
- item.innerHTML = '<span class="log-time">' + new Date().toLocaleTimeString() + '</span>' +
- '<span class="log-port">[:' + data.port + ']</span>' +
- '<span class="status-' + data.status + '">' + data.status + '</span>';
- logList.insertBefore(item, logList.firstChild);
-
- while (logList.children.length > 50) {
- logList.removeChild(logList.lastChild);
- }
- }
- connect();
- </script>
- </body>
- </html>`
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.Write([]byte(html))
- }
|