feat(channel): KOOK 渠道适配器 + 框架兼容增强(wsutil/httpclient)
- plugins/channels/kook: config/adapter/gateway/websocket/send/message/errors — 实现 PlatformAdapter 13方法 - WS 有状态网关: 取gateway地址→连WS→信令0/1/2/3/4/6 + 30s心跳/6s超时 + resume(拼接sn/session_id) + 指数退避重连 - 收事件: 信令0 → UnifiedMessage(word注 channel_type/type/target_id/extra.author→字段) - 发消息: /message/create(频道) + /direct-message/create(私聊,修正正确端点,非user-chat) + Bearer鉴权 - 注册 channels.go + CHANNELS_JSON 多账号 + channelbridge.configured 加 kook(bot_token非空才连) - 框架增强: internal/channel/adapter/wsutil(连接管理/心跳/重连/resume骨架,复用gorilla,KOOK用上) + httpclient(Bearer+envelope归一,KOOK用) - 全仓 go build/vet/test 绿, 零新依赖(复用餐gorilla), 未动telegram/qq/weixin/webhook契约 - §4.6 隔离/黑白名单/第三方边界未破坏 注: KOOK WS/WH 双模式待补(ReceiveMode), 实测需主人提供 CHANNEL_KOOK_TOKEN
This commit is contained in:
1 parent
eab6b63eb0
commit
764d592859
24 files changed
+2800
-2
No files matched your search
@@ -0,0 +1,220 @@
|
||||
package kook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/adapter"
|
||||
)
|
||||
|
||||
func TestParseSignal(t *testing.T) {
|
||||
t.Parallel()
|
||||
s := []byte(`{"s":1,"d":{"code":0,"session_id":"sess-123"}}`)
|
||||
sig, err := parseSignal(s)
|
||||
if err != nil {
|
||||
t.Fatalf("parseSignal: %v", err)
|
||||
}
|
||||
if sig.S != signalHello {
|
||||
t.Errorf("S = %d, want %d (hello)", sig.S, signalHello)
|
||||
}
|
||||
if len(sig.D) == 0 {
|
||||
t.Error("D should carry the hello payload")
|
||||
}
|
||||
|
||||
s0 := []byte(`{"s":0,"sn":7,"d":{"channel_type":"GROUP"}}`)
|
||||
sig0, err := parseSignal(s0)
|
||||
if err != nil {
|
||||
t.Fatalf("parseSignal event: %v", err)
|
||||
}
|
||||
if sig0.S != signalEvent || sig0.SN != 7 {
|
||||
t.Errorf("event S/SN = %d/%d, want 0/7", sig0.S, sig0.SN)
|
||||
}
|
||||
|
||||
if sig, err := parseSignal([]byte(`{"s":3}`)); err != nil || sig.S != signalPong {
|
||||
t.Errorf("pong parse = %+v, %v", sig, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeartbeatFrame(t *testing.T) {
|
||||
t.Parallel()
|
||||
b, err := heartbeatFrame(42)
|
||||
if err != nil {
|
||||
t.Fatalf("heartbeatFrame: %v", err)
|
||||
}
|
||||
if string(b) != `{"s":2,"sn":42}` {
|
||||
t.Errorf("heartbeat frame = %s, want {\"s\":2,\"sn\":42}", string(b))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayURL_FreshNoResume(t *testing.T) {
|
||||
t.Parallel()
|
||||
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != gatewayPath {
|
||||
http.Error(w, "unexpected", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
kookOK(w, map[string]any{"url": "wss://gw.example.com/gateway?compress=0&token=abc"})
|
||||
})
|
||||
a, _ := newTestAdapter(t, h)
|
||||
got, err := a.gatewayURL(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("gatewayURL: %v", err)
|
||||
}
|
||||
if got != "wss://gw.example.com/gateway?compress=0&token=abc" {
|
||||
t.Errorf("fresh url = %q, want unchanged base", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayURL_ResumeAddsParams(t *testing.T) {
|
||||
t.Parallel()
|
||||
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != gatewayPath {
|
||||
http.Error(w, "unexpected", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
kookOK(w, map[string]any{"url": "wss://gw.example.com/gateway?compress=0&token=abc"})
|
||||
})
|
||||
a, _ := newTestAdapter(t, h)
|
||||
a.setSession("sess-abc", 5)
|
||||
assertCanResume(t, a, true)
|
||||
|
||||
got, err := a.gatewayURL(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("gatewayURL: %v", err)
|
||||
}
|
||||
u, err := url.Parse(got)
|
||||
if err != nil {
|
||||
t.Fatalf("parse resume url: %v", err)
|
||||
}
|
||||
q := u.Query()
|
||||
if q.Get("compress") != "0" || q.Get("token") != "abc" {
|
||||
t.Errorf("existing query params lost: %q", got)
|
||||
}
|
||||
if q.Get("resume") != "1" || q.Get("sn") != "5" || q.Get("session_id") != "sess-abc" {
|
||||
t.Errorf("resume params = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayURL_ResetDropsResume(t *testing.T) {
|
||||
t.Parallel()
|
||||
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
kookOK(w, map[string]any{"url": "wss://gw.example.com/gateway?compress=0"})
|
||||
})
|
||||
a, _ := newTestAdapter(t, h)
|
||||
a.setSession("sess-abc", 5)
|
||||
a.resetSession()
|
||||
assertCanResume(t, a, false)
|
||||
got, err := a.gatewayURL(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("gatewayURL: %v", err)
|
||||
}
|
||||
if strings.Contains(got, "resume=1") {
|
||||
t.Errorf("reset session should not emit resume params: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func assertCanResume(t *testing.T, a *Adapter, want bool) {
|
||||
t.Helper()
|
||||
if got := a.canResume(); got != want {
|
||||
t.Fatalf("canResume = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConnect_GatewayDeliversEvent is an end-to-end smoke of the gateway path: an
|
||||
// httptest server serves the REST gateway lookup, upgrades a WebSocket, sends a
|
||||
// hello then an s=0 event, and the adapter dispatches the normalized message to
|
||||
// the push handler.
|
||||
func TestConnect_GatewayDeliversEvent(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
delivered []adapter.UnifiedMessage
|
||||
)
|
||||
got := make(chan adapter.UnifiedMessage, 1)
|
||||
|
||||
var srv *httptest.Server
|
||||
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case gatewayPath:
|
||||
wsURL := "ws://" + strings.TrimPrefix(srv.URL, "http://") + "/ws"
|
||||
kookOK(w, map[string]any{"url": wsURL})
|
||||
case "/ws":
|
||||
conn, err := wsUpgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
t.Errorf("ws upgrade: %v", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.WriteJSON(map[string]any{"s": 1, "d": map[string]any{"code": 0, "session_id": "sess-123"}})
|
||||
_ = conn.WriteJSON(map[string]any{"s": 0, "sn": 7, "d": map[string]any{
|
||||
"channel_type": "GROUP", "type": 1, "target_id": "chan-8", "author_id": "u-8",
|
||||
"content": "gateway hi", "msg_id": "m-8", "msg_timestamp": 1700000000000, "nonce": "",
|
||||
"extra": map[string]any{
|
||||
"guild_id": "g-8", "channel_name": "test",
|
||||
"author": map[string]any{"id": "u-8", "username": "u", "nickname": "Nick"},
|
||||
},
|
||||
}})
|
||||
// Hold the connection and consume client frames (heartbeat/close).
|
||||
for {
|
||||
if _, _, err := conn.ReadMessage(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
})
|
||||
srv = httptest.NewServer(h)
|
||||
defer srv.Close()
|
||||
|
||||
a := New(
|
||||
Config{BotToken: "testtoken"},
|
||||
WithBaseURL(srv.URL),
|
||||
WithHTTPClient(srv.Client()),
|
||||
WithLogger(discardLogger()),
|
||||
)
|
||||
a.SetMessageHandler(func(ctx context.Context, msg adapter.UnifiedMessage) {
|
||||
mu.Lock()
|
||||
delivered = append(delivered, msg)
|
||||
mu.Unlock()
|
||||
select {
|
||||
case got <- msg:
|
||||
default:
|
||||
}
|
||||
})
|
||||
|
||||
if err := a.Connect(context.Background()); err != nil {
|
||||
t.Fatalf("Connect: %v", err)
|
||||
}
|
||||
defer func() { _ = a.Disconnect(context.Background()) }()
|
||||
|
||||
select {
|
||||
case msg := <-got:
|
||||
if msg.Platform != "kook" {
|
||||
t.Errorf("Platform = %q, want kook", msg.Platform)
|
||||
}
|
||||
if msg.ChannelID != "chan-8" || msg.GroupID != "g-8" {
|
||||
t.Errorf("ChannelID/GroupID = %q/%q, want chan-8/g-8", msg.ChannelID, msg.GroupID)
|
||||
}
|
||||
if msg.SenderName != "Nick" || msg.SenderID != "u-8" {
|
||||
t.Errorf("Sender = %q/%q, want Nick/u-8", msg.SenderName, msg.SenderID)
|
||||
}
|
||||
if msg.Content != "gateway hi" || msg.ContentType != adapter.ContentText {
|
||||
t.Errorf("Content = %q/%q, want gateway hi/text", msg.Content, msg.ContentType)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for gateway event")
|
||||
}
|
||||
|
||||
if sn := a.currentSN(); sn != 7 {
|
||||
t.Errorf("currentSN = %d, want 7", sn)
|
||||
}
|
||||
if sid := a.currentSession(); sid != "sess-123" {
|
||||
t.Errorf("currentSession = %q, want sess-123", sid)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user