|
| 1 | +package chat |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "strings" |
| 8 | + "sync" |
| 9 | + |
| 10 | + "github.com/chaitin/koalaqa/model" |
| 11 | + "github.com/chaitin/koalaqa/pkg/crypt" |
| 12 | + "github.com/chaitin/koalaqa/pkg/glog" |
| 13 | +) |
| 14 | + |
| 15 | +type streamState struct { |
| 16 | + mutex sync.Mutex |
| 17 | + question string |
| 18 | + stream strings.Builder |
| 19 | + Done bool |
| 20 | +} |
| 21 | + |
| 22 | +func (s *streamState) Append(data string, done bool) { |
| 23 | + s.mutex.Lock() |
| 24 | + defer s.mutex.Unlock() |
| 25 | + |
| 26 | + if data != "" { |
| 27 | + s.stream.WriteString(data) |
| 28 | + } |
| 29 | + |
| 30 | + if done { |
| 31 | + s.Done = done |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func (s *streamState) Text() string { |
| 36 | + s.mutex.Lock() |
| 37 | + defer s.mutex.Unlock() |
| 38 | + |
| 39 | + return s.stream.String() |
| 40 | +} |
| 41 | + |
| 42 | +type wecom struct { |
| 43 | + logger *glog.Logger |
| 44 | + cache sync.Map |
| 45 | + cfg model.SystemChatConfig |
| 46 | + botCallback BotCallback |
| 47 | +} |
| 48 | + |
| 49 | +func (w *wecom) verify(req VerifyReq) (string, error) { |
| 50 | + wx, _, err := crypt.NewWXBizJsonMsgCrypt(w.cfg.ClientID, w.cfg.ClientSecret, "") |
| 51 | + if err != nil { |
| 52 | + return "", err |
| 53 | + } |
| 54 | + code, str := wx.VerifyURL(req.Signature, req.Timestamp, req.Nonce, req.Content) |
| 55 | + err = crypt.WecomErrorByCode(code) |
| 56 | + if err != nil { |
| 57 | + return "", err |
| 58 | + } |
| 59 | + |
| 60 | + return str, nil |
| 61 | +} |
| 62 | + |
| 63 | +type userReq struct { |
| 64 | + Msgid string `json:"msgid"` |
| 65 | + Aibotid string `json:"aibotid"` |
| 66 | + Chattype string `json:"chattype"` |
| 67 | + From struct { |
| 68 | + Userid string `json:"userid"` |
| 69 | + } `json:"from"` |
| 70 | + Msgtype string `json:"msgtype"` |
| 71 | + Text struct { |
| 72 | + Content string `json:"content"` |
| 73 | + } `json:"text"` |
| 74 | + Stream struct { |
| 75 | + Id string `json:"id"` |
| 76 | + } `json:"stream"` |
| 77 | +} |
| 78 | + |
| 79 | +type userResp struct { |
| 80 | + Msgtype string `json:"msgtype"` |
| 81 | + Stream weComStream `json:"stream"` |
| 82 | +} |
| 83 | + |
| 84 | +type weComStream struct { |
| 85 | + Id string `json:"id"` |
| 86 | + Finish bool `json:"finish"` |
| 87 | + Content string `json:"content"` |
| 88 | + MsgItem []struct { |
| 89 | + Msgtype string `json:"msgtype"` |
| 90 | + Image struct { |
| 91 | + Base64 string `json:"base64"` |
| 92 | + Md5 string `json:"md5"` |
| 93 | + } `json:"image"` |
| 94 | + } `json:"msg_item"` |
| 95 | +} |
| 96 | + |
| 97 | +func (w *wecom) decryptUserReq(ctx context.Context, req VerifyReq) (*userReq, error) { |
| 98 | + wx, _, err := crypt.NewWXBizJsonMsgCrypt( |
| 99 | + w.cfg.ClientID, |
| 100 | + w.cfg.ClientSecret, |
| 101 | + "", |
| 102 | + ) |
| 103 | + if err != nil { |
| 104 | + return nil, err |
| 105 | + } |
| 106 | + |
| 107 | + code, reqMsg := wx.DecryptMsg(req.Content, req.Signature, req.Timestamp, req.Nonce) |
| 108 | + err = crypt.WecomErrorByCode(code) |
| 109 | + if err != nil { |
| 110 | + return nil, err |
| 111 | + } |
| 112 | + logger := w.logger.WithContext(ctx).With("req", reqMsg) |
| 113 | + logger.Info("recv wecom req") |
| 114 | + var data userReq |
| 115 | + err = json.Unmarshal([]byte(reqMsg), &data) |
| 116 | + if err != nil { |
| 117 | + return nil, err |
| 118 | + } |
| 119 | + |
| 120 | + return &data, nil |
| 121 | +} |
| 122 | + |
| 123 | +func (w *wecom) EncryptUserRes(ctx context.Context, nonce string, data weComStream) (string, error) { |
| 124 | + wx, _, err := crypt.NewWXBizJsonMsgCrypt( |
| 125 | + w.cfg.ClientID, |
| 126 | + w.cfg.ClientSecret, |
| 127 | + "", |
| 128 | + ) |
| 129 | + if err != nil { |
| 130 | + return "", err |
| 131 | + } |
| 132 | + |
| 133 | + respBytes, err := json.Marshal(userResp{ |
| 134 | + Msgtype: "stream", |
| 135 | + Stream: data, |
| 136 | + }) |
| 137 | + if err != nil { |
| 138 | + return "", err |
| 139 | + } |
| 140 | + |
| 141 | + code, msg := wx.EncryptMsg(string(respBytes), nonce) |
| 142 | + err = crypt.WecomErrorByCode(code) |
| 143 | + if err != nil { |
| 144 | + return "", err |
| 145 | + } |
| 146 | + |
| 147 | + return msg, nil |
| 148 | +} |
| 149 | + |
| 150 | +func (w *wecom) StreamText(ctx context.Context, req VerifyReq) (string, error) { |
| 151 | + if req.OnlyVerify { |
| 152 | + return w.verify(req) |
| 153 | + } |
| 154 | + |
| 155 | + logger := w.logger.WithContext(ctx) |
| 156 | + |
| 157 | + decryptReq, err := w.decryptUserReq(ctx, req) |
| 158 | + if err != nil { |
| 159 | + logger.WithErr(err).Error("decrypt user req failed") |
| 160 | + return "", err |
| 161 | + } |
| 162 | + |
| 163 | + logger = logger.With("req", decryptReq) |
| 164 | + |
| 165 | + switch decryptReq.Msgtype { |
| 166 | + case "text": |
| 167 | + state := &streamState{ |
| 168 | + question: decryptReq.Text.Content, |
| 169 | + mutex: sync.Mutex{}, |
| 170 | + stream: strings.Builder{}, |
| 171 | + Done: true, |
| 172 | + } |
| 173 | + _, loaded := w.cache.LoadOrStore(decryptReq.Msgid, state) |
| 174 | + if !loaded { |
| 175 | + stream, err := w.botCallback(ctx, BotReq{ |
| 176 | + SessionID: "wecom_" + decryptReq.Msgid, |
| 177 | + Question: state.question, |
| 178 | + }) |
| 179 | + if err != nil { |
| 180 | + logger.WithErr(err).Error("bot callback failed") |
| 181 | + state.Append("出错了,请稍后再试", true) |
| 182 | + } else { |
| 183 | + go func() { |
| 184 | + stream.Read(context.Background(), func(content string) { |
| 185 | + state.Append(content, false) |
| 186 | + }) |
| 187 | + |
| 188 | + state.Append("", true) |
| 189 | + }() |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + resp, err := w.EncryptUserRes(ctx, req.Nonce, weComStream{ |
| 194 | + Id: decryptReq.Msgid, |
| 195 | + Finish: false, |
| 196 | + Content: "<think>正在查找相关信息...</think>", |
| 197 | + }) |
| 198 | + if err != nil { |
| 199 | + logger.WithErr(err).Error("encrypt wecom user res failed") |
| 200 | + return "", err |
| 201 | + } |
| 202 | + |
| 203 | + return resp, nil |
| 204 | + case "stream": |
| 205 | + stateI, ok := w.cache.Load(decryptReq.Stream.Id) |
| 206 | + if !ok { |
| 207 | + logger.Warn("msg not exist") |
| 208 | + resp, err := w.EncryptUserRes(ctx, req.Nonce, weComStream{ |
| 209 | + Id: decryptReq.Stream.Id, |
| 210 | + Finish: true, |
| 211 | + Content: "出错了,请稍后再试", |
| 212 | + }) |
| 213 | + if err != nil { |
| 214 | + logger.WithErr(err).Warn("encrypt user res failed") |
| 215 | + return "", err |
| 216 | + } |
| 217 | + return resp, nil |
| 218 | + } |
| 219 | + |
| 220 | + state := stateI.(*streamState) |
| 221 | + content := state.Text() |
| 222 | + |
| 223 | + if content == "" { |
| 224 | + content = "<think>正在查找相关信息...</think>" |
| 225 | + } |
| 226 | + |
| 227 | + if state.Done { |
| 228 | + w.cache.Delete(decryptReq.Stream.Id) |
| 229 | + } |
| 230 | + |
| 231 | + resp, err := w.EncryptUserRes(ctx, req.Nonce, weComStream{ |
| 232 | + Id: decryptReq.Stream.Id, |
| 233 | + Finish: state.Done, |
| 234 | + Content: content, |
| 235 | + }) |
| 236 | + if err != nil { |
| 237 | + logger.WithErr(err).Error("encrypt user res failed") |
| 238 | + return "", err |
| 239 | + } |
| 240 | + return resp, nil |
| 241 | + } |
| 242 | + |
| 243 | + return "", errors.ErrUnsupported |
| 244 | +} |
| 245 | + |
| 246 | +func (w *wecom) Start() error { |
| 247 | + return nil |
| 248 | +} |
| 249 | + |
| 250 | +func (w *wecom) Stop() {} |
| 251 | + |
| 252 | +func newWecom(cfg model.SystemChatConfig, callback BotCallback) (Bot, error) { |
| 253 | + return &wecom{ |
| 254 | + logger: glog.Module("chat", "wecom"), |
| 255 | + cache: sync.Map{}, |
| 256 | + cfg: cfg, |
| 257 | + botCallback: callback, |
| 258 | + }, nil |
| 259 | +} |
0 commit comments