feat: 增加 SafeW 已监控群列表接口

通过 getUpdates 将群写入 Redis,供创建/编辑渠道时选择 chat_id,避免前端重复传递 token。
This commit is contained in:
2026-08-15 00:40:40 +08:00
parent 0d0cd0c510
commit bd8a9ff96d
14 changed files with 2265 additions and 4 deletions
+85 -2
View File
@@ -2,11 +2,16 @@ package handler
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
"aiaa-notification-service/internal/adapter"
"aiaa-notification-service/internal/cache"
"aiaa-notification-service/internal/model"
"aiaa-notification-service/internal/safew"
"aiaa-notification-service/internal/store"
"github.com/gin-gonic/gin"
@@ -15,10 +20,11 @@ import (
type ChannelHandler struct {
store *store.Store
cache *cache.Cache
chats *safew.Watcher
}
func NewChannelHandler(s *store.Store, c *cache.Cache) *ChannelHandler {
return &ChannelHandler{store: s, cache: c}
func NewChannelHandler(s *store.Store, c *cache.Cache, w *safew.Watcher) *ChannelHandler {
return &ChannelHandler{store: s, cache: c, chats: w}
}
type createChannelReq struct {
@@ -96,3 +102,80 @@ func (h *ChannelHandler) Delete(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}
type listSafewChatsReq struct {
Token string `json:"token"`
Q string `json:"q"`
}
func (h *ChannelHandler) ListSafewChats(c *gin.Context) {
var req listSafewChatsReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
h.respondSafewChats(c, strings.TrimSpace(req.Token), req.Q)
}
func (h *ChannelHandler) ListChannelSafewChats(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
ch, err := h.store.GetChannel(c.Request.Context(), id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
return
}
token, err := safewTokenFromChannel(ch)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
h.respondSafewChats(c, token, c.Query("q"))
}
func (h *ChannelHandler) respondSafewChats(c *gin.Context, token, q string) {
if token == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "safew token is required"})
return
}
if h.chats == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "safew chat list unavailable"})
return
}
h.chats.Ensure(token)
if err := h.chats.Refresh(c.Request.Context(), token); err != nil {
if _, ok := err.(*adapter.SafewAuthError); ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
slog.Warn("safew refresh", "error", err)
}
list, err := h.chats.List(c.Request.Context(), token, q)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if list == nil {
list = []adapter.SafewChat{}
}
c.JSON(http.StatusOK, gin.H{"data": list, "total": len(list)})
}
func safewTokenFromChannel(ch *model.Channel) (string, error) {
if ch.Type != "safew" {
return "", fmt.Errorf("channel is not safew")
}
if ch.Config == nil {
return "", fmt.Errorf("safew token is required")
}
var cfg struct {
Token string `json:"token"`
}
if err := json.Unmarshal(*ch.Config, &cfg); err != nil {
return "", fmt.Errorf("safew token is required")
}
token := strings.TrimSpace(cfg.Token)
if token == "" {
return "", fmt.Errorf("safew token is required")
}
return token, nil
}
+72
View File
@@ -0,0 +1,72 @@
package handler
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"aiaa-notification-service/internal/adapter"
"aiaa-notification-service/internal/model"
"aiaa-notification-service/internal/safew"
"github.com/gin-gonic/gin"
)
func TestListSafewChatsPOSTMissingToken(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &ChannelHandler{chats: safew.NewWatcher(safew.NewMemStore(), func(string, int64, int) ([]adapter.SafewChat, int64, error) {
return nil, 0, nil
})}
r := gin.New()
r.POST("/api/v1/channels/safew/chats", h.ListSafewChats)
req := httptest.NewRequest(http.MethodPost, "/api/v1/channels/safew/chats", bytes.NewReader([]byte(`{}`)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
}
}
func TestListSafewChatsPOSTOk(t *testing.T) {
gin.SetMode(gin.TestMode)
st := safew.NewMemStore()
_ = st.MergeSafewChats(nil, "tok", []adapter.SafewChat{{ID: "10000778141", Type: "group", Title: "测试AI"}})
h := &ChannelHandler{chats: safew.NewWatcher(st, func(string, int64, int) ([]adapter.SafewChat, int64, error) {
return nil, 0, nil
})}
r := gin.New()
r.POST("/api/v1/channels/safew/chats", h.ListSafewChats)
req := httptest.NewRequest(http.MethodPost, "/api/v1/channels/safew/chats", bytes.NewReader([]byte(`{"token":"tok","q":"测试"}`)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
}
var resp struct {
Data []adapter.SafewChat `json:"data"`
Total int `json:"total"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if resp.Total != 1 || resp.Data[0].ID != "10000778141" {
t.Fatalf("%#v", resp)
}
}
func TestSafewTokenFromChannel(t *testing.T) {
raw := json.RawMessage(`{"token":"abc","chat_id":"1"}`)
ch := &model.Channel{Type: "safew", Config: &raw}
tok, err := safewTokenFromChannel(ch)
if err != nil || tok != "abc" {
t.Fatalf("%q %v", tok, err)
}
ch.Type = "bark"
if _, err := safewTokenFromChannel(ch); err == nil {
t.Fatal("expected not safew")
}
}