mirror of
https://github.com/yibaiba/hideck.git
synced 2026-12-06 00:01:20 +00:00
feat(notify): connect Weixin command channel
Why: QR credentials were persisted but could not yet receive commands or deliver notifications. Why this works: a cancellable iLink long poll processes authorized messages before advancing its durable cursor, binds only the first direct user, echoes context tokens, and routes commands through the shared handlers. Remaining: production WeChat message verification needs a scanned account, and media upload follows in the next mission issue.
This commit is contained in:
1 parent
045f455e46
commit
93b8da01ea
11 files changed
+843
-14
No files matched your search
@@ -93,14 +93,13 @@ func (s *Server) applyWeixinQRCredentials(credentials notify.WeixinQRCredentials
|
||||
if s.notifyMgr == nil {
|
||||
return "通知管理器不可用,凭证尚未保存"
|
||||
}
|
||||
state, err := s.notifyMgr.LoadRuntimeState()
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
state.Weixin.AccountID = credentials.AccountID
|
||||
state.Weixin.Token = credentials.Token
|
||||
state.Weixin.UserID = credentials.UserID
|
||||
if err := s.notifyMgr.SaveRuntimeState(state); err != nil {
|
||||
if err := s.notifyMgr.UpdateRuntimeState(func(state *notify.RuntimeState) error {
|
||||
state.Weixin.AccountID = credentials.AccountID
|
||||
state.Weixin.Token = credentials.Token
|
||||
state.Weixin.BaseURL = credentials.BaseURL
|
||||
state.Weixin.UserID = credentials.UserID
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
nextConfig := *s.fullCfg
|
||||
|
||||
@@ -232,9 +232,10 @@ type QQConfig struct {
|
||||
}
|
||||
|
||||
type WeixinConfig struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
BaseURL string `mapstructure:"base_url"`
|
||||
AllowedUserIDs []string `mapstructure:"allowed_user_ids"`
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
BaseURL string `mapstructure:"base_url"`
|
||||
AllowedUserIDs []string `mapstructure:"allowed_user_ids"`
|
||||
AllowedGroupIDs []string `mapstructure:"allowed_group_ids"`
|
||||
}
|
||||
|
||||
type WeComBotConfig struct {
|
||||
|
||||
@@ -44,9 +44,10 @@ func UpdateNotificationInFile(path string, notifications NotificationConfigs) er
|
||||
}
|
||||
|
||||
root["weixin"] = map[string]any{
|
||||
"enabled": notifications.Weixin.Enabled,
|
||||
"base_url": notifications.Weixin.BaseURL,
|
||||
"allowed_user_ids": notifications.Weixin.AllowedUserIDs,
|
||||
"enabled": notifications.Weixin.Enabled,
|
||||
"base_url": notifications.Weixin.BaseURL,
|
||||
"allowed_user_ids": notifications.Weixin.AllowedUserIDs,
|
||||
"allowed_group_ids": notifications.Weixin.AllowedGroupIDs,
|
||||
}
|
||||
|
||||
root["wecom_bot"] = map[string]any{
|
||||
|
||||
@@ -88,6 +88,13 @@ func (m *Manager) SaveRuntimeState(state RuntimeState) error {
|
||||
return m.stateStore.Save(state)
|
||||
}
|
||||
|
||||
func (m *Manager) UpdateRuntimeState(update func(*RuntimeState) error) error {
|
||||
if m == nil || m.stateStore == nil {
|
||||
return ErrRuntimeStateStoreUnavailable
|
||||
}
|
||||
return m.stateStore.Update(update)
|
||||
}
|
||||
|
||||
// initChannels 根据配置创建并启动所有通知渠道
|
||||
func (m *Manager) initChannels(cfg *config.Config) error {
|
||||
m.channels = nil
|
||||
@@ -128,6 +135,18 @@ func (m *Manager) initChannels(cfg *config.Config) error {
|
||||
}
|
||||
}
|
||||
|
||||
// 个人微信 iLink 渠道
|
||||
if cfg.Weixin.Enabled {
|
||||
weixin, err := NewWeixinChannel(WeixinChannelOptions{Config: cfg.Weixin, StateStore: m.stateStore})
|
||||
if err != nil {
|
||||
logger.Error("初始化个人微信通知渠道失败", "err", err)
|
||||
return err
|
||||
}
|
||||
if weixin != nil {
|
||||
m.channels = append(m.channels, weixin)
|
||||
}
|
||||
}
|
||||
|
||||
// Webhook 渠道
|
||||
if cfg.Webhook.Enabled {
|
||||
wh, err := NewWebhookChannel(cfg.Webhook)
|
||||
|
||||
@@ -16,6 +16,7 @@ var ErrRuntimeStateStoreUnavailable = errors.New("通知渠道运行状态存储
|
||||
type WeixinRuntimeState struct {
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
BaseURL string `json:"base_url,omitempty"`
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
SyncBuffer string `json:"sync_buffer,omitempty"`
|
||||
ContextTokens map[string]string `json:"context_tokens,omitempty"`
|
||||
@@ -44,6 +45,7 @@ type RuntimeState struct {
|
||||
type RuntimeStateStore interface {
|
||||
Load() (RuntimeState, error)
|
||||
Save(state RuntimeState) error
|
||||
Update(update func(*RuntimeState) error) error
|
||||
}
|
||||
|
||||
type FileRuntimeStateStore struct {
|
||||
@@ -58,6 +60,10 @@ func NewFileRuntimeStateStore(path string) *FileRuntimeStateStore {
|
||||
func (s *FileRuntimeStateStore) Load() (RuntimeState, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.loadLocked()
|
||||
}
|
||||
|
||||
func (s *FileRuntimeStateStore) loadLocked() (RuntimeState, error) {
|
||||
data, err := os.ReadFile(s.path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return newRuntimeState(), nil
|
||||
@@ -78,6 +84,26 @@ func (s *FileRuntimeStateStore) Load() (RuntimeState, error) {
|
||||
func (s *FileRuntimeStateStore) Save(state RuntimeState) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.saveLocked(state)
|
||||
}
|
||||
|
||||
func (s *FileRuntimeStateStore) Update(update func(*RuntimeState) error) error {
|
||||
if update == nil {
|
||||
return errors.New("通知渠道运行状态更新函数不能为空")
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
state, err := s.loadLocked()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := update(&state); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.saveLocked(state)
|
||||
}
|
||||
|
||||
func (s *FileRuntimeStateStore) saveLocked(state RuntimeState) error {
|
||||
state = cloneRuntimeState(state)
|
||||
state.Version = runtimeStateVersion
|
||||
data, err := json.MarshalIndent(state, "", " ")
|
||||
|
||||
@@ -51,3 +51,25 @@ func TestFileRuntimeStateStoreReturnsEmptyStateWhenMissing(t *testing.T) {
|
||||
t.Fatalf("Load() = %+v, %v", state, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileRuntimeStateStoreUpdatePreservesOtherChannels(t *testing.T) {
|
||||
store := NewFileRuntimeStateStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
state := newRuntimeState()
|
||||
state.QQ.AdminOpenID = "qq-admin"
|
||||
if err := store.Save(state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Update(func(current *RuntimeState) error {
|
||||
current.Weixin.DefaultTarget = "wx-user"
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := store.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loaded.QQ.AdminOpenID != "qq-admin" || loaded.Weixin.DefaultTarget != "wx-user" {
|
||||
t.Fatalf("updated state = %+v", loaded)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yibaiba/hideck/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
weixinRetryDelay = 2 * time.Second
|
||||
weixinBackoffDelay = 30 * time.Second
|
||||
weixinSessionDelay = 10 * time.Minute
|
||||
)
|
||||
|
||||
type WeixinChannelOptions struct {
|
||||
Config config.WeixinConfig
|
||||
StateStore RuntimeStateStore
|
||||
HTTPClient *http.Client
|
||||
}
|
||||
|
||||
type WeixinChannel struct {
|
||||
config config.WeixinConfig
|
||||
stateStore RuntimeStateStore
|
||||
client *weixinMessageClient
|
||||
|
||||
commandMu sync.RWMutex
|
||||
commands map[string]CommandHandler
|
||||
stateMu sync.RWMutex
|
||||
state RuntimeState
|
||||
runMu sync.Mutex
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
type weixinAuthorizationRequest struct {
|
||||
Kind string
|
||||
ChatID string
|
||||
Sender string
|
||||
ContextToken string
|
||||
}
|
||||
|
||||
func NewWeixinChannel(options WeixinChannelOptions) (*WeixinChannel, error) {
|
||||
if !options.Config.Enabled {
|
||||
return nil, nil
|
||||
}
|
||||
if options.StateStore == nil {
|
||||
return nil, ErrRuntimeStateStoreUnavailable
|
||||
}
|
||||
state, err := options.StateStore.Load()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(state.Weixin.AccountID) == "" || strings.TrimSpace(state.Weixin.Token) == "" {
|
||||
return nil, errors.New("个人微信已启用,但尚未完成扫码登录")
|
||||
}
|
||||
return &WeixinChannel{
|
||||
config: options.Config, stateStore: options.StateStore,
|
||||
client: newWeixinMessageClient(options.HTTPClient), commands: make(map[string]CommandHandler), state: state,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) Name() string { return "weixin" }
|
||||
|
||||
func (w *WeixinChannel) Send(text string) error {
|
||||
state := w.snapshotState()
|
||||
target := strings.TrimSpace(state.Weixin.DefaultTarget)
|
||||
if target == "" {
|
||||
return errors.New("个人微信尚未绑定默认通知目标")
|
||||
}
|
||||
return w.sendTo(context.Background(), target, text)
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) RegisterCommand(name string, handler CommandHandler) {
|
||||
name = strings.ToLower(strings.TrimSpace(name))
|
||||
if name == "" || handler == nil {
|
||||
return
|
||||
}
|
||||
w.commandMu.Lock()
|
||||
w.commands[name] = handler
|
||||
w.commandMu.Unlock()
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) Start() error {
|
||||
w.runMu.Lock()
|
||||
if w.cancel != nil {
|
||||
w.runMu.Unlock()
|
||||
return errors.New("个人微信消息监听已经启动")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
w.cancel, w.done = cancel, done
|
||||
w.runMu.Unlock()
|
||||
defer close(done)
|
||||
return w.pollLoop(ctx)
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) Close() error {
|
||||
w.runMu.Lock()
|
||||
cancel, done := w.cancel, w.done
|
||||
w.cancel, w.done = nil, nil
|
||||
w.runMu.Unlock()
|
||||
if cancel == nil {
|
||||
return nil
|
||||
}
|
||||
cancel()
|
||||
<-done
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) authorizeMessage(request weixinAuthorizationRequest) (bool, error) {
|
||||
state := w.snapshotState()
|
||||
if request.Kind == "group" {
|
||||
if !containsString(w.config.AllowedGroupIDs, request.ChatID) || !w.allowedDirect(state, request.Sender) {
|
||||
return false, nil
|
||||
}
|
||||
} else if !w.allowedDirect(state, request.Sender) {
|
||||
if len(w.config.AllowedUserIDs) > 0 || len(state.Weixin.AllowedUsers) > 0 || state.Weixin.DefaultTarget != "" {
|
||||
return false, nil
|
||||
}
|
||||
state.Weixin.AllowedUsers = append(state.Weixin.AllowedUsers, request.Sender)
|
||||
state.Weixin.DefaultTarget = request.Sender
|
||||
}
|
||||
if strings.TrimSpace(request.ContextToken) != "" {
|
||||
if state.Weixin.ContextTokens == nil {
|
||||
state.Weixin.ContextTokens = make(map[string]string)
|
||||
}
|
||||
state.Weixin.ContextTokens[request.ChatID] = strings.TrimSpace(request.ContextToken)
|
||||
}
|
||||
if err := w.saveState(state); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) executeMessage(ctx context.Context, chatID, text string) error {
|
||||
name, args, err := parseCommand(text)
|
||||
if errors.Is(err, ErrInvalidCommand) {
|
||||
return w.sendTo(ctx, chatID, "请发送 /help 查看可用命令")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.commandMu.RLock()
|
||||
handler := w.commands[name]
|
||||
w.commandMu.RUnlock()
|
||||
if handler == nil {
|
||||
return w.sendTo(ctx, chatID, unknownCommandReply(text))
|
||||
}
|
||||
commandContext := &weixinCommandContext{channel: w, target: chatID}
|
||||
defer commandContext.release()
|
||||
response := handler(commandContext, args)
|
||||
if response != "" {
|
||||
if err := commandContext.respond(ctx, response); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) sendTo(ctx context.Context, target, text string) error {
|
||||
state := w.snapshotState()
|
||||
contextToken := state.Weixin.ContextTokens[strings.TrimSpace(target)]
|
||||
return w.client.sendText(ctx, weixinSendTextRequest{
|
||||
Credentials: weixinCredentials(state), Target: strings.TrimSpace(target),
|
||||
Text: text, ContextToken: contextToken,
|
||||
})
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) allowedDirect(state RuntimeState, userID string) bool {
|
||||
return containsString(w.config.AllowedUserIDs, userID) || containsString(state.Weixin.AllowedUsers, userID)
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) snapshotState() RuntimeState {
|
||||
w.stateMu.RLock()
|
||||
defer w.stateMu.RUnlock()
|
||||
return cloneRuntimeState(w.state)
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) updateState(update func(*RuntimeState)) error {
|
||||
state := w.snapshotState()
|
||||
update(&state)
|
||||
return w.saveState(state)
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) saveState(state RuntimeState) error {
|
||||
var stored RuntimeState
|
||||
if err := w.stateStore.Update(func(current *RuntimeState) error {
|
||||
current.Weixin = cloneRuntimeState(state).Weixin
|
||||
stored = cloneRuntimeState(*current)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
w.stateMu.Lock()
|
||||
w.state = stored
|
||||
w.stateMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func weixinCredentials(state RuntimeState) WeixinQRCredentials {
|
||||
return WeixinQRCredentials{
|
||||
AccountID: state.Weixin.AccountID, Token: state.Weixin.Token,
|
||||
BaseURL: state.WeixinBaseURL(), UserID: state.Weixin.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
func (s RuntimeState) WeixinBaseURL() string {
|
||||
if strings.TrimSpace(s.Weixin.BaseURL) != "" {
|
||||
return s.Weixin.BaseURL
|
||||
}
|
||||
return DefaultWeixinBaseURL
|
||||
}
|
||||
|
||||
func containsString(values []string, target string) bool {
|
||||
target = strings.TrimSpace(target)
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func pollRetryDelay(failures int) time.Duration {
|
||||
if failures >= 3 {
|
||||
return weixinBackoffDelay
|
||||
}
|
||||
return weixinRetryDelay
|
||||
}
|
||||
|
||||
func weixinResponseError(response weixinUpdatesResponse) (time.Duration, error) {
|
||||
if response.Ret == 0 && response.ErrCode == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
delay := weixinRetryDelay
|
||||
if response.Ret == -14 || response.ErrCode == -14 {
|
||||
delay = weixinSessionDelay
|
||||
}
|
||||
return delay, fmt.Errorf("ret=%d errcode=%d errmsg=%s", response.Ret, response.ErrCode, response.ErrMsg)
|
||||
}
|
||||
|
||||
func waitContext(ctx context.Context, delay time.Duration) bool {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/yibaiba/hideck/pkg/logger"
|
||||
)
|
||||
|
||||
type weixinCommandContext struct {
|
||||
channel *WeixinChannel
|
||||
target string
|
||||
stateMu sync.Mutex
|
||||
sendMu sync.Mutex
|
||||
released bool
|
||||
pending []string
|
||||
}
|
||||
|
||||
func (c *weixinCommandContext) Reply(text string) {
|
||||
if c == nil || c.channel == nil {
|
||||
return
|
||||
}
|
||||
c.stateMu.Lock()
|
||||
if !c.released {
|
||||
c.pending = append(c.pending, text)
|
||||
c.stateMu.Unlock()
|
||||
return
|
||||
}
|
||||
c.stateMu.Unlock()
|
||||
go func() {
|
||||
if err := c.respond(context.Background(), text); err != nil {
|
||||
logger.Warn("回复个人微信命令消息失败", "err", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (c *weixinCommandContext) release() {
|
||||
c.stateMu.Lock()
|
||||
if c.released {
|
||||
c.stateMu.Unlock()
|
||||
return
|
||||
}
|
||||
c.released = true
|
||||
pending := append([]string(nil), c.pending...)
|
||||
c.pending = nil
|
||||
c.stateMu.Unlock()
|
||||
for _, text := range pending {
|
||||
if err := c.respond(context.Background(), text); err != nil {
|
||||
logger.Warn("回复个人微信命令消息失败", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *weixinCommandContext) respond(ctx context.Context, text string) error {
|
||||
c.sendMu.Lock()
|
||||
defer c.sendMu.Unlock()
|
||||
return c.channel.sendTo(ctx, c.target, text)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
weixinChannelVersion = "2.2.0"
|
||||
weixinLongPollTimeout = 35_000
|
||||
weixinMessageUser = 1
|
||||
weixinMessageBot = 2
|
||||
weixinMessageFinished = 2
|
||||
weixinItemText = 1
|
||||
)
|
||||
|
||||
type weixinMessageClient struct {
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type weixinUpdatesResponse struct {
|
||||
Ret int `json:"ret"`
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
GetUpdatesBuffer string `json:"get_updates_buf"`
|
||||
LongPollingTimeout int `json:"longpolling_timeout_ms"`
|
||||
Messages []weixinMessage `json:"msgs"`
|
||||
}
|
||||
|
||||
type weixinMessage struct {
|
||||
FromUserID string `json:"from_user_id"`
|
||||
ToUserID string `json:"to_user_id"`
|
||||
RoomID string `json:"room_id"`
|
||||
ChatRoomID string `json:"chat_room_id"`
|
||||
MessageID string `json:"message_id"`
|
||||
ContextToken string `json:"context_token"`
|
||||
MessageType int `json:"message_type"`
|
||||
MsgType int `json:"msg_type"`
|
||||
Items []weixinMessageItem `json:"item_list"`
|
||||
}
|
||||
|
||||
type weixinMessageItem struct {
|
||||
Type int `json:"type"`
|
||||
TextItem struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"text_item"`
|
||||
}
|
||||
|
||||
type weixinAPIResponse struct {
|
||||
Ret int `json:"ret"`
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
type weixinSendTextRequest struct {
|
||||
Credentials WeixinQRCredentials
|
||||
Target string
|
||||
Text string
|
||||
ContextToken string
|
||||
}
|
||||
|
||||
type weixinPostRequest struct {
|
||||
Credentials WeixinQRCredentials
|
||||
Endpoint string
|
||||
Payload map[string]any
|
||||
Target any
|
||||
}
|
||||
|
||||
func newWeixinMessageClient(client *http.Client) *weixinMessageClient {
|
||||
return &weixinMessageClient{httpClient: newWeixinILinkClient(client).httpClient}
|
||||
}
|
||||
|
||||
func (c *weixinMessageClient) getUpdates(ctx context.Context, credentials WeixinQRCredentials, syncBuffer string) (weixinUpdatesResponse, error) {
|
||||
var response weixinUpdatesResponse
|
||||
err := c.post(ctx, weixinPostRequest{
|
||||
Credentials: credentials, Endpoint: "/ilink/bot/getupdates",
|
||||
Payload: map[string]any{"get_updates_buf": syncBuffer}, Target: &response,
|
||||
})
|
||||
return response, err
|
||||
}
|
||||
|
||||
func (c *weixinMessageClient) sendText(ctx context.Context, input weixinSendTextRequest) error {
|
||||
if strings.TrimSpace(input.Text) == "" {
|
||||
return errors.New("微信消息内容不能为空")
|
||||
}
|
||||
clientID, err := randomHex(16)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
message := map[string]any{
|
||||
"from_user_id": "", "to_user_id": input.Target, "client_id": "vohive-weixin-" + clientID,
|
||||
"message_type": weixinMessageBot, "message_state": weixinMessageFinished,
|
||||
"item_list": []any{map[string]any{"type": weixinItemText, "text_item": map[string]string{"text": input.Text}}},
|
||||
}
|
||||
if strings.TrimSpace(input.ContextToken) != "" {
|
||||
message["context_token"] = input.ContextToken
|
||||
}
|
||||
var response weixinAPIResponse
|
||||
if err := c.post(ctx, weixinPostRequest{
|
||||
Credentials: input.Credentials, Endpoint: "/ilink/bot/sendmessage",
|
||||
Payload: map[string]any{"msg": message}, Target: &response,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if response.Ret != 0 || response.ErrCode != 0 {
|
||||
return fmt.Errorf("iLink sendmessage 失败: ret=%d errcode=%d errmsg=%s", response.Ret, response.ErrCode, response.ErrMsg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *weixinMessageClient) post(ctx context.Context, input weixinPostRequest) error {
|
||||
input.Payload["base_info"] = map[string]string{"channel_version": weixinChannelVersion}
|
||||
body, err := json.Marshal(input.Payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(input.Credentials.BaseURL, "/")+input.Endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
setWeixinMessageHeaders(request, input.Credentials.Token, len(body))
|
||||
response, err := c.httpClient.Do(request)
|
||||
if err != nil {
|
||||
return fmt.Errorf("iLink %s 请求失败: %w", input.Endpoint, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return fmt.Errorf("iLink %s 请求失败: HTTP %d", input.Endpoint, response.StatusCode)
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(response.Body, weixinQRResponseMax)).Decode(input.Target); err != nil {
|
||||
return fmt.Errorf("解析 iLink %s 响应失败: %w", input.Endpoint, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func setWeixinMessageHeaders(request *http.Request, token string, contentLength int) {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("AuthorizationType", "ilink_bot_token")
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
request.Header.Set("Content-Length", strconv.Itoa(contentLength))
|
||||
request.Header.Set("X-WECHAT-UIN", randomWeixinUIN())
|
||||
request.Header.Set("iLink-App-Id", "bot")
|
||||
request.Header.Set("iLink-App-ClientVersion", "131584")
|
||||
}
|
||||
|
||||
func randomWeixinUIN() string {
|
||||
value := make([]byte, 4)
|
||||
if _, err := rand.Read(value); err != nil {
|
||||
return ""
|
||||
}
|
||||
decimal := strconv.FormatUint(uint64(binary.BigEndian.Uint32(value)), 10)
|
||||
return base64.StdEncoding.EncodeToString([]byte(decimal))
|
||||
}
|
||||
|
||||
func (m weixinMessage) text() string {
|
||||
for _, item := range m.Items {
|
||||
if item.Type == weixinItemText && strings.TrimSpace(item.TextItem.Text) != "" {
|
||||
return strings.TrimSpace(item.TextItem.Text)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m weixinMessage) chat(accountID string) (kind, id string) {
|
||||
roomID := strings.TrimSpace(m.RoomID)
|
||||
if roomID == "" {
|
||||
roomID = strings.TrimSpace(m.ChatRoomID)
|
||||
}
|
||||
msgType := m.MsgType
|
||||
if msgType == 0 {
|
||||
msgType = m.MessageType
|
||||
}
|
||||
toUserID := strings.TrimSpace(m.ToUserID)
|
||||
if roomID != "" || (toUserID != "" && toUserID != accountID && msgType == weixinMessageUser) {
|
||||
if roomID == "" {
|
||||
roomID = toUserID
|
||||
}
|
||||
return "group", roomID
|
||||
}
|
||||
return "direct", strings.TrimSpace(m.FromUserID)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/yibaiba/hideck/pkg/logger"
|
||||
)
|
||||
|
||||
func (w *WeixinChannel) pollLoop(ctx context.Context) error {
|
||||
failures := 0
|
||||
for {
|
||||
state := w.snapshotState()
|
||||
response, err := w.client.getUpdates(ctx, weixinCredentials(state), state.Weixin.SyncBuffer)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
failures++
|
||||
logger.Warn("个人微信长轮询失败", "attempt", failures, "err", err)
|
||||
if !waitContext(ctx, pollRetryDelay(failures)) {
|
||||
return nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
if delay, err := weixinResponseError(response); err != nil {
|
||||
logger.Warn("个人微信长轮询返回错误", "err", err)
|
||||
if !waitContext(ctx, delay) {
|
||||
return nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
failures = 0
|
||||
if err := w.processUpdates(ctx, response); err != nil {
|
||||
logger.Warn("处理个人微信消息失败,保留旧游标等待重试", "err", err)
|
||||
if !waitContext(ctx, weixinRetryDelay) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) processUpdates(ctx context.Context, response weixinUpdatesResponse) error {
|
||||
for _, message := range response.Messages {
|
||||
if err := w.processMessage(ctx, message); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(response.GetUpdatesBuffer) == "" {
|
||||
return nil
|
||||
}
|
||||
return w.updateState(func(state *RuntimeState) {
|
||||
state.Weixin.SyncBuffer = response.GetUpdatesBuffer
|
||||
})
|
||||
}
|
||||
|
||||
func (w *WeixinChannel) processMessage(ctx context.Context, message weixinMessage) error {
|
||||
sender := strings.TrimSpace(message.FromUserID)
|
||||
text := message.text()
|
||||
state := w.snapshotState()
|
||||
if sender == "" || sender == state.Weixin.AccountID || text == "" {
|
||||
return nil
|
||||
}
|
||||
chatKind, chatID := message.chat(state.Weixin.AccountID)
|
||||
allowed, err := w.authorizeMessage(weixinAuthorizationRequest{
|
||||
Kind: chatKind, ChatID: chatID, Sender: sender, ContextToken: message.ContextToken,
|
||||
})
|
||||
if err != nil || !allowed {
|
||||
return err
|
||||
}
|
||||
return w.executeMessage(ctx, chatID, text)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yibaiba/hideck/internal/config"
|
||||
)
|
||||
|
||||
func TestWeixinChannelBindsFirstDirectMessageAndExecutesHelp(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
updateCalls := 0
|
||||
sentBodies := make(chan map[string]any, 2)
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/ilink/bot/getupdates":
|
||||
mu.Lock()
|
||||
updateCalls++
|
||||
call := updateCalls
|
||||
mu.Unlock()
|
||||
if call > 1 {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
_, _ = w.Write([]byte(`{"ret":0}`))
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"ret": 0, "get_updates_buf": "cursor-2",
|
||||
"msgs": []any{map[string]any{
|
||||
"from_user_id": "user-1", "to_user_id": "bot-1", "message_id": "message-1",
|
||||
"message_type": 1, "context_token": "context-1",
|
||||
"item_list": []any{map[string]any{"type": 1, "text_item": map[string]string{"text": "/help"}}},
|
||||
}},
|
||||
})
|
||||
case "/ilink/bot/sendmessage":
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decode send body: %v", err)
|
||||
}
|
||||
sentBodies <- body
|
||||
_, _ = w.Write([]byte(`{"ret":0,"errcode":0}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer provider.Close()
|
||||
store := NewFileRuntimeStateStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
state := newRuntimeState()
|
||||
state.Weixin = WeixinRuntimeState{AccountID: "bot-1", Token: "token-1", BaseURL: provider.URL}
|
||||
if err := store.Save(state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
channel, err := NewWeixinChannel(WeixinChannelOptions{
|
||||
Config: config.WeixinConfig{Enabled: true, BaseURL: provider.URL}, StateStore: store, HTTPClient: provider.Client(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
channel.RegisterCommand("help", func(_ CommandContext, _ []string) string {
|
||||
return "可用设备(1)\n- modem-01 主卡\n\n命令帮助"
|
||||
})
|
||||
startResult := make(chan error, 1)
|
||||
go func() { startResult <- channel.Start() }()
|
||||
|
||||
var sent map[string]any
|
||||
select {
|
||||
case sent = <-sentBodies:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("help response was not sent")
|
||||
}
|
||||
waitUntil(t, 2*time.Second, func() bool {
|
||||
state, err := store.Load()
|
||||
return err == nil && state.Weixin.SyncBuffer == "cursor-2"
|
||||
})
|
||||
if err := channel.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-startResult; err != nil {
|
||||
t.Fatalf("Start() error = %v", err)
|
||||
}
|
||||
message := sent["msg"].(map[string]any)
|
||||
if message["to_user_id"] != "user-1" || message["context_token"] != "context-1" {
|
||||
t.Fatalf("sent message = %#v", message)
|
||||
}
|
||||
loaded, err := store.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loaded.Weixin.DefaultTarget != "user-1" || loaded.Weixin.SyncBuffer != "cursor-2" || loaded.Weixin.ContextTokens["user-1"] != "context-1" {
|
||||
t.Fatalf("saved state = %+v", loaded.Weixin)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeixinChannelGroupCannotClaimFirstBinding(t *testing.T) {
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/ilink/bot/sendmessage" {
|
||||
t.Error("unauthorized group triggered a reply")
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"ret":0}`))
|
||||
}))
|
||||
defer provider.Close()
|
||||
store := NewFileRuntimeStateStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
state := newRuntimeState()
|
||||
state.Weixin = WeixinRuntimeState{AccountID: "bot-1", Token: "token-1", BaseURL: provider.URL}
|
||||
if err := store.Save(state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
channel, err := NewWeixinChannel(WeixinChannelOptions{
|
||||
Config: config.WeixinConfig{Enabled: true, BaseURL: provider.URL}, StateStore: store, HTTPClient: provider.Client(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message := weixinMessage{FromUserID: "user-1", ToUserID: "group-1", RoomID: "group-1", MessageType: 1}
|
||||
message.Items = textWeixinItems("/help")
|
||||
if err := channel.processMessage(context.Background(), message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := store.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loaded.Weixin.DefaultTarget != "" || len(loaded.Weixin.AllowedUsers) != 0 {
|
||||
t.Fatalf("group claimed binding: %+v", loaded.Weixin)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeixinChannelUsesPersistedCursorAfterRestart(t *testing.T) {
|
||||
cursorSeen := make(chan string, 1)
|
||||
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Cursor string `json:"get_updates_buf"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
select {
|
||||
case cursorSeen <- body.Cursor:
|
||||
default:
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
_, _ = w.Write([]byte(`{"ret":0}`))
|
||||
}))
|
||||
defer provider.Close()
|
||||
store := NewFileRuntimeStateStore(filepath.Join(t.TempDir(), "state.json"))
|
||||
state := newRuntimeState()
|
||||
state.Weixin = WeixinRuntimeState{
|
||||
AccountID: "bot-1", Token: "token-1", BaseURL: provider.URL, SyncBuffer: "saved-cursor",
|
||||
}
|
||||
if err := store.Save(state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
channel, err := NewWeixinChannel(WeixinChannelOptions{
|
||||
Config: config.WeixinConfig{Enabled: true}, StateStore: store, HTTPClient: provider.Client(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
startResult := make(chan error, 1)
|
||||
go func() { startResult <- channel.Start() }()
|
||||
select {
|
||||
case cursor := <-cursorSeen:
|
||||
if cursor != "saved-cursor" {
|
||||
t.Fatalf("cursor = %q", cursor)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("getupdates was not called")
|
||||
}
|
||||
_ = channel.Close()
|
||||
if err := <-startResult; err != nil && !strings.Contains(err.Error(), "context canceled") {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func textWeixinItems(text string) []weixinMessageItem {
|
||||
item := weixinMessageItem{Type: weixinItemText}
|
||||
item.TextItem.Text = text
|
||||
return []weixinMessageItem{item}
|
||||
}
|
||||
Reference in new issue
Block a user