api.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. package api
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/gorilla/websocket"
  10. "AI-Status-Light/internal/database"
  11. "AI-Status-Light/internal/logger"
  12. )
  13. type Server struct {
  14. db *database.DB
  15. server *http.Server
  16. clients map[*websocket.Conn]bool
  17. clientsMu sync.Mutex
  18. upgrader websocket.Upgrader
  19. }
  20. type Response struct {
  21. Code int `json:"code"`
  22. Message string `json:"message"`
  23. Data interface{} `json:"data,omitempty"`
  24. }
  25. func New(db *database.DB, addr string) *Server {
  26. s := &Server{
  27. db: db,
  28. clients: make(map[*websocket.Conn]bool),
  29. upgrader: websocket.Upgrader{
  30. CheckOrigin: func(r *http.Request) bool {
  31. return true
  32. },
  33. },
  34. }
  35. mux := http.NewServeMux()
  36. mux.HandleFunc("/api/mqtt", s.handleMQTT)
  37. mux.HandleFunc("/api/mqtt/", s.handleMQTTByID)
  38. mux.HandleFunc("/api/health", s.handleHealth)
  39. mux.HandleFunc("/ws", s.handleWebSocket)
  40. mux.HandleFunc("/", s.handleIndex)
  41. s.server = &http.Server{
  42. Addr: addr,
  43. Handler: corsMiddleware(mux),
  44. }
  45. return s
  46. }
  47. func (s *Server) Start() error {
  48. logger.Info("API 服务器开始监听: %s", s.server.Addr)
  49. err := s.server.ListenAndServe()
  50. if err != nil && err != http.ErrServerClosed {
  51. logger.Error("API 服务器监听失败: %v", err)
  52. }
  53. return err
  54. }
  55. func corsMiddleware(next http.Handler) http.Handler {
  56. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  57. w.Header().Set("Access-Control-Allow-Origin", "*")
  58. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
  59. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  60. if r.Method == "OPTIONS" {
  61. w.WriteHeader(http.StatusOK)
  62. return
  63. }
  64. next.ServeHTTP(w, r)
  65. })
  66. }
  67. func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
  68. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok"})
  69. }
  70. func (s *Server) handleMQTT(w http.ResponseWriter, r *http.Request) {
  71. logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
  72. switch r.Method {
  73. case http.MethodGet:
  74. s.listMQTTConfigs(w, r)
  75. case http.MethodPost:
  76. s.createMQTTConfig(w, r)
  77. default:
  78. logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
  79. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  80. }
  81. }
  82. func (s *Server) handleMQTTByID(w http.ResponseWriter, r *http.Request) {
  83. logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
  84. idStr := strings.TrimPrefix(r.URL.Path, "/api/mqtt/")
  85. id, err := strconv.Atoi(idStr)
  86. if err != nil {
  87. logger.Warn("无效的配置 ID: %s", idStr)
  88. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的 ID"})
  89. return
  90. }
  91. switch r.Method {
  92. case http.MethodGet:
  93. s.getMQTTConfig(w, id)
  94. case http.MethodPut:
  95. s.updateMQTTConfig(w, r, id)
  96. case http.MethodDelete:
  97. s.deleteMQTTConfig(w, id)
  98. default:
  99. logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
  100. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  101. }
  102. }
  103. func (s *Server) listMQTTConfigs(w http.ResponseWriter, r *http.Request) {
  104. configs, err := s.db.ListMQTTConfigs()
  105. if err != nil {
  106. logger.Error("查询 MQTT 配置列表失败: %v", err)
  107. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  108. return
  109. }
  110. logger.Debug("查询 MQTT 配置列表: %d 条", len(configs))
  111. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: configs})
  112. }
  113. func (s *Server) createMQTTConfig(w http.ResponseWriter, r *http.Request) {
  114. var cfg database.MQTTConfig
  115. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  116. logger.Warn("创建配置请求体解析失败: %v", err)
  117. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  118. return
  119. }
  120. if cfg.Broker == "" {
  121. logger.Warn("创建配置: broker 为空")
  122. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "broker 不能为空"})
  123. return
  124. }
  125. if cfg.ClientID == "" {
  126. cfg.ClientID = "opencode-monitor"
  127. }
  128. if cfg.Topic == "" {
  129. cfg.Topic = "opencode/status"
  130. }
  131. if err := s.db.SaveMQTTConfig(&cfg); err != nil {
  132. logger.Error("创建 MQTT 配置失败: %v", err)
  133. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  134. return
  135. }
  136. logger.Info("MQTT 配置已创建: id=%d, broker=%s, topic=%s", cfg.ID, cfg.Broker, cfg.Topic)
  137. writeJSON(w, http.StatusCreated, Response{Code: 0, Message: "创建成功", Data: cfg})
  138. }
  139. func (s *Server) getMQTTConfig(w http.ResponseWriter, id int) {
  140. configs, err := s.db.ListMQTTConfigs()
  141. if err != nil {
  142. logger.Error("查询 MQTT 配置失败: id=%d, %v", id, err)
  143. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  144. return
  145. }
  146. for _, cfg := range configs {
  147. if cfg.ID == id {
  148. logger.Debug("查询 MQTT 配置: id=%d", id)
  149. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: cfg})
  150. return
  151. }
  152. }
  153. logger.Warn("MQTT 配置不存在: id=%d", id)
  154. writeJSON(w, http.StatusNotFound, Response{Code: -1, Message: "配置不存在"})
  155. }
  156. func (s *Server) updateMQTTConfig(w http.ResponseWriter, r *http.Request, id int) {
  157. var cfg database.MQTTConfig
  158. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  159. logger.Warn("更新配置请求体解析失败: id=%d, %v", id, err)
  160. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  161. return
  162. }
  163. cfg.ID = id
  164. if cfg.Broker == "" {
  165. logger.Warn("更新配置: broker 为空, id=%d", id)
  166. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "broker 不能为空"})
  167. return
  168. }
  169. if cfg.ClientID == "" {
  170. cfg.ClientID = "opencode-monitor"
  171. }
  172. if cfg.Topic == "" {
  173. cfg.Topic = "opencode/status"
  174. }
  175. if err := s.db.SaveMQTTConfig(&cfg); err != nil {
  176. logger.Error("更新 MQTT 配置失败: id=%d, %v", id, err)
  177. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  178. return
  179. }
  180. logger.Info("MQTT 配置已更新: id=%d, broker=%s, topic=%s", id, cfg.Broker, cfg.Topic)
  181. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "更新成功", Data: cfg})
  182. }
  183. func (s *Server) deleteMQTTConfig(w http.ResponseWriter, id int) {
  184. if err := s.db.DeleteMQTTConfig(id); err != nil {
  185. logger.Error("删除 MQTT 配置失败: id=%d, %v", id, err)
  186. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  187. return
  188. }
  189. logger.Info("MQTT 配置已删除: id=%d", id)
  190. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "删除成功"})
  191. }
  192. func writeJSON(w http.ResponseWriter, statusCode int, data interface{}) {
  193. w.Header().Set("Content-Type", "application/json")
  194. w.WriteHeader(statusCode)
  195. json.NewEncoder(w).Encode(data)
  196. }
  197. func (s *Server) GetAddr() string {
  198. return s.server.Addr
  199. }
  200. func (s *Server) handleWebSocket(w http.ResponseWriter, r *http.Request) {
  201. conn, err := s.upgrader.Upgrade(w, r, nil)
  202. if err != nil {
  203. logger.Error("WebSocket 升级失败: %v", err)
  204. return
  205. }
  206. s.clientsMu.Lock()
  207. s.clients[conn] = true
  208. s.clientsMu.Unlock()
  209. logger.Info("WebSocket 客户端已连接,当前连接数: %d", len(s.clients))
  210. go func() {
  211. defer func() {
  212. s.clientsMu.Lock()
  213. delete(s.clients, conn)
  214. s.clientsMu.Unlock()
  215. conn.Close()
  216. logger.Info("WebSocket 客户端已断开,当前连接数: %d", len(s.clients))
  217. }()
  218. for {
  219. _, _, err := conn.ReadMessage()
  220. if err != nil {
  221. break
  222. }
  223. }
  224. }()
  225. }
  226. func (s *Server) BroadcastStatus(port int, status string, code string) {
  227. s.clientsMu.Lock()
  228. defer s.clientsMu.Unlock()
  229. if len(s.clients) == 0 {
  230. return
  231. }
  232. payload := map[string]interface{}{
  233. "port": port,
  234. "status": status,
  235. "code": code,
  236. "timestamp": time.Now().Format(time.RFC3339),
  237. }
  238. data, err := json.Marshal(payload)
  239. if err != nil {
  240. logger.Error("序列化广播消息失败: %v", err)
  241. return
  242. }
  243. for client := range s.clients {
  244. err := client.WriteMessage(websocket.TextMessage, data)
  245. if err != nil {
  246. logger.Debug("WebSocket 写入失败,移除客户端: %v", err)
  247. client.Close()
  248. delete(s.clients, client)
  249. }
  250. }
  251. }
  252. func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
  253. if r.URL.Path != "/" {
  254. http.NotFound(w, r)
  255. return
  256. }
  257. html := `<!DOCTYPE html>
  258. <html lang="zh-CN">
  259. <head>
  260. <meta charset="UTF-8">
  261. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  262. <title>OpenCode Monitor</title>
  263. <style>
  264. * { margin: 0; padding: 0; box-sizing: border-box; }
  265. body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; padding: 20px; }
  266. .container { max-width: 1200px; margin: 0 auto; }
  267. h1 { color: #333; margin-bottom: 20px; }
  268. .status-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }
  269. .status-card { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
  270. .status-card h2 { color: #666; font-size: 14px; margin-bottom: 8px; }
  271. .status-value { font-size: 32px; font-weight: bold; margin-bottom: 8px; }
  272. .status-time { color: #999; font-size: 12px; }
  273. .status-空闲 { color: #52c41a; }
  274. .status-忙碌 { color: #ff4d4f; }
  275. .status-思考中 { color: #faad14; }
  276. .status-运行中 { color: #1890ff; }
  277. .status-完成 { color: #52c41a; }
  278. .status-错误 { color: #ff4d4f; }
  279. .status-重试中 { color: #faad14; }
  280. .status-修改中 { color: #722ed1; }
  281. .log { margin-top: 20px; background: white; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
  282. .log h2 { color: #666; font-size: 14px; margin-bottom: 12px; }
  283. .log-list { max-height: 300px; overflow-y: auto; }
  284. .log-item { padding: 8px 0; border-bottom: 1px solid #f0f0f0; font-size: 14px; }
  285. .log-item:last-child { border-bottom: none; }
  286. .log-time { color: #999; margin-right: 8px; }
  287. .log-port { color: #1890ff; margin-right: 8px; }
  288. .connected { color: #52c41a; font-size: 12px; margin-left: 10px; }
  289. .disconnected { color: #ff4d4f; font-size: 12px; margin-left: 10px; }
  290. </style>
  291. </head>
  292. <body>
  293. <div class="container">
  294. <h1>OpenCode Monitor <span id="connectionStatus" class="disconnected">● 未连接</span></h1>
  295. <div class="status-grid" id="statusGrid">
  296. <div class="status-card">
  297. <h2>当前状态</h2>
  298. <div class="status-value" id="currentStatus">等待中...</div>
  299. <div class="status-time" id="statusTime"></div>
  300. </div>
  301. </div>
  302. <div class="log">
  303. <h2>状态日志</h2>
  304. <div class="log-list" id="logList"></div>
  305. </div>
  306. </div>
  307. <script>
  308. const statusGrid = document.getElementById('statusGrid');
  309. const logList = document.getElementById('logList');
  310. const currentStatus = document.getElementById('currentStatus');
  311. const statusTime = document.getElementById('statusTime');
  312. const connectionStatus = document.getElementById('connectionStatus');
  313. let ws = null;
  314. let reconnectTimer = null;
  315. function connect() {
  316. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  317. ws = new WebSocket(protocol + '//' + window.location.host + '/ws');
  318. ws.onopen = function() {
  319. connectionStatus.textContent = '● 已连接';
  320. connectionStatus.className = 'connected';
  321. if (reconnectTimer) {
  322. clearTimeout(reconnectTimer);
  323. reconnectTimer = null;
  324. }
  325. };
  326. ws.onmessage = function(event) {
  327. try {
  328. const data = JSON.parse(event.data);
  329. updateStatus(data);
  330. addLog(data);
  331. } catch (e) {
  332. console.error('解析消息失败:', e);
  333. }
  334. };
  335. ws.onclose = function() {
  336. connectionStatus.textContent = '● 未连接';
  337. connectionStatus.className = 'disconnected';
  338. reconnectTimer = setTimeout(connect, 3000);
  339. };
  340. ws.onerror = function() {
  341. ws.close();
  342. };
  343. }
  344. function updateStatus(data) {
  345. currentStatus.textContent = data.status;
  346. currentStatus.className = 'status-value status-' + data.status;
  347. statusTime.textContent = '端口: ' + data.port + ' | 更新时间: ' + new Date().toLocaleTimeString();
  348. }
  349. function addLog(data) {
  350. const item = document.createElement('div');
  351. item.className = 'log-item';
  352. item.innerHTML = '<span class="log-time">' + new Date().toLocaleTimeString() + '</span>' +
  353. '<span class="log-port">[:' + data.port + ']</span>' +
  354. '<span class="status-' + data.status + '">' + data.status + '</span>';
  355. logList.insertBefore(item, logList.firstChild);
  356. while (logList.children.length > 50) {
  357. logList.removeChild(logList.lastChild);
  358. }
  359. }
  360. connect();
  361. </script>
  362. </body>
  363. </html>`
  364. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  365. w.Write([]byte(html))
  366. }