api.go 12 KB

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