-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
websocket.go
401 lines (382 loc) · 12.6 KB
/
websocket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package server
import (
"fmt"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
wsc "golang.org/x/net/websocket"
"net/http"
"strconv"
"strings"
"sync"
"time"
)
type websocketServer struct {
bot *coolq.CQBot
token string
eventConn []*websocket.Conn
pushLock *sync.Mutex
handshake string
}
type websocketClient struct {
conf *global.GoCQReverseWebsocketConfig
token string
bot *coolq.CQBot
pushLock *sync.Mutex
universalConn *wsc.Conn
eventConn *wsc.Conn
}
var WebsocketServer = &websocketServer{}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (s *websocketServer) Run(addr, authToken string, b *coolq.CQBot) {
s.token = authToken
s.pushLock = new(sync.Mutex)
s.bot = b
s.handshake = fmt.Sprintf(`{"_post_method":2,"meta_event_type":"lifecycle","post_type":"meta_event","self_id":%d,"sub_type":"connect","time":%d}`,
s.bot.Client.Uin, time.Now().Unix())
b.OnEventPush(s.onBotPushEvent)
http.HandleFunc("/event", s.event)
http.HandleFunc("/api", s.api)
http.HandleFunc("/", s.any)
go func() {
log.Infof("CQ Websocket 服务器已启动: %v", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}()
}
func NewWebsocketClient(conf *global.GoCQReverseWebsocketConfig, authToken string, b *coolq.CQBot) *websocketClient {
return &websocketClient{conf: conf, token: authToken, bot: b, pushLock: new(sync.Mutex)}
}
func (c *websocketClient) Run() {
if !c.conf.Enabled {
return
}
if c.conf.ReverseApiUrl != "" {
c.connectApi()
}
if c.conf.ReverseEventUrl != "" {
c.connectEvent()
}
if c.conf.ReverseUrl != "" {
c.connectUniversal()
}
c.bot.OnEventPush(c.onBotPushEvent)
}
func (c *websocketClient) connectApi() {
log.Infof("开始尝试连接到反向Websocket API服务器: %v", c.conf.ReverseApiUrl)
wsConf, err := wsc.NewConfig(c.conf.ReverseApiUrl, c.conf.ReverseApiUrl)
if err != nil {
log.Warnf("连接到反向Websocket API服务器 %v 时出现致命错误: %v", c.conf.ReverseApiUrl, err)
return
}
wsConf.Header["X-Client-Role"] = []string{"API"}
wsConf.Header["X-Self-ID"] = []string{strconv.FormatInt(c.bot.Client.Uin, 10)}
wsConf.Header["User-Agent"] = []string{"CQHttp/4.15.0"}
if c.token != "" {
wsConf.Header["Authorization"] = []string{"Token " + c.token}
}
conn, err := wsc.DialConfig(wsConf)
if err != nil {
log.Warnf("连接到反向Websocket API服务器 %v 时出现错误: %v", c.conf.ReverseApiUrl, err)
if c.conf.ReverseReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
c.connectApi()
}
return
}
log.Infof("已连接到反向Websocket API服务器 %v", c.conf.ReverseApiUrl)
go c.listenApi(conn, false)
}
func (c *websocketClient) connectEvent() {
log.Infof("开始尝试连接到反向Websocket Event服务器: %v", c.conf.ReverseEventUrl)
wsConf, err := wsc.NewConfig(c.conf.ReverseEventUrl, c.conf.ReverseEventUrl)
if err != nil {
log.Warnf("连接到反向Websocket Event服务器 %v 时出现致命错误: %v", c.conf.ReverseApiUrl, err)
return
}
wsConf.Header["X-Client-Role"] = []string{"Event"}
wsConf.Header["X-Self-ID"] = []string{strconv.FormatInt(c.bot.Client.Uin, 10)}
wsConf.Header["User-Agent"] = []string{"CQHttp/4.15.0"}
if c.token != "" {
wsConf.Header["Authorization"] = []string{"Token " + c.token}
}
conn, err := wsc.DialConfig(wsConf)
if err != nil {
log.Warnf("连接到反向Websocket API服务器 %v 时出现错误: %v", c.conf.ReverseApiUrl, err)
if c.conf.ReverseReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
c.connectApi()
}
return
}
log.Infof("已连接到反向Websocket Event服务器 %v", c.conf.ReverseEventUrl)
c.eventConn = conn
}
func (c *websocketClient) connectUniversal() {
log.Infof("开始尝试连接到反向Websocket Universal服务器: %v", c.conf.ReverseUrl)
wsConf, err := wsc.NewConfig(c.conf.ReverseUrl, c.conf.ReverseUrl)
if err != nil {
log.Warnf("连接到反向Websocket Universal服务器 %v 时出现致命错误: %v", c.conf.ReverseUrl, err)
return
}
wsConf.Header["X-Client-Role"] = []string{"Universal"}
wsConf.Header["X-Self-ID"] = []string{strconv.FormatInt(c.bot.Client.Uin, 10)}
wsConf.Header["User-Agent"] = []string{"CQHttp/4.15.0"}
if c.token != "" {
wsConf.Header["Authorization"] = []string{"Token " + c.token}
}
conn, err := wsc.DialConfig(wsConf)
if err != nil {
log.Warnf("连接到反向Websocket Universal服务器 %v 时出现错误: %v", c.conf.ReverseUrl, err)
if c.conf.ReverseReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
c.connectUniversal()
}
return
}
go c.listenApi(conn, true)
c.universalConn = conn
}
func (c *websocketClient) listenApi(conn *wsc.Conn, u bool) {
defer conn.Close()
for {
buf := make([]byte, 10240)
l, err := conn.Read(buf)
if err != nil {
break
}
j := gjson.ParseBytes(buf[:l])
t := strings.ReplaceAll(j.Get("action").Str, "_async", "")
if f, ok := wsApi[t]; ok {
ret := f(c.bot, j.Get("params"))
if j.Get("echo").Exists() {
ret["echo"] = j.Get("echo").Value()
}
_, _ = conn.Write([]byte(ret.ToJson()))
}
}
if c.conf.ReverseReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
if u {
c.connectUniversal()
return
}
c.connectApi()
}
}
func (c *websocketClient) onBotPushEvent(m coolq.MSG) {
c.pushLock.Lock()
defer c.pushLock.Unlock()
if c.eventConn != nil {
if _, err := c.eventConn.Write([]byte(m.ToJson())); err != nil {
_ = c.eventConn.Close()
if c.conf.ReverseReconnectInterval != 0 {
time.Sleep(time.Millisecond * time.Duration(c.conf.ReverseReconnectInterval))
c.connectEvent()
}
}
}
if c.universalConn != nil {
_, _ = c.universalConn.Write([]byte(m.ToJson()))
}
}
func (s *websocketServer) event(w http.ResponseWriter, r *http.Request) {
if s.token != "" {
if r.URL.Query().Get("access_token") != s.token && strings.SplitN(r.Header.Get("Authorization"), " ", 2)[1] != s.token {
log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr)
w.WriteHeader(401)
return
}
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Warnf("处理 Websocket 请求时出现错误: %v", err)
return
}
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake))
if err == nil {
log.Infof("接受 Websocket 连接: %v (/event)", r.RemoteAddr)
s.eventConn = append(s.eventConn, c)
}
}
func (s *websocketServer) api(w http.ResponseWriter, r *http.Request) {
if s.token != "" {
if r.URL.Query().Get("access_token") != s.token && strings.SplitN(r.Header.Get("Authorization"), " ", 2)[1] != s.token {
log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr)
w.WriteHeader(401)
return
}
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Warnf("处理 Websocket 请求时出现错误: %v", err)
return
}
log.Infof("接受 Websocket 连接: %v (/api)", r.RemoteAddr)
go s.listenApi(c)
}
func (s *websocketServer) any(w http.ResponseWriter, r *http.Request) {
if s.token != "" {
if r.URL.Query().Get("access_token") != s.token && strings.SplitN(r.Header.Get("Authorization"), " ", 2)[1] != s.token {
log.Warnf("已拒绝 %v 的 Websocket 请求: Token错误", r.RemoteAddr)
w.WriteHeader(401)
return
}
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Warnf("处理 Websocket 请求时出现错误: %v", err)
return
}
err = c.WriteMessage(websocket.TextMessage, []byte(s.handshake))
if err == nil {
log.Infof("接受 Websocket 连接: %v (/)", r.RemoteAddr)
s.eventConn = append(s.eventConn, c)
s.listenApi(c)
}
}
func (s *websocketServer) listenApi(c *websocket.Conn) {
defer c.Close()
for {
t, payload, err := c.ReadMessage()
if err != nil {
break
}
if t == websocket.TextMessage {
j := gjson.ParseBytes(payload)
t := strings.ReplaceAll(j.Get("action").Str, "_async", "") //TODO: async support
//log.Infof("API调用: %v", j.Get("action").Str)
if f, ok := wsApi[t]; ok {
ret := f(s.bot, j.Get("params"))
if j.Get("echo").Exists() {
ret["echo"] = j.Get("echo").Value()
}
_ = c.WriteJSON(ret)
}
}
}
}
func (s *websocketServer) onBotPushEvent(m coolq.MSG) {
s.pushLock.Lock()
defer s.pushLock.Unlock()
pos := 0
for _, conn := range s.eventConn {
err := conn.WriteMessage(websocket.TextMessage, []byte(m.ToJson()))
if err != nil {
_ = conn.Close()
s.eventConn = append(s.eventConn[:pos], s.eventConn[pos+1:]...)
if pos > 0 {
pos++
}
}
pos++
}
}
var wsApi = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
"get_login_info": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetLoginInfo()
},
"get_friend_list": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetFriendList()
},
"get_group_list": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetGroupList()
},
"get_group_info": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetGroupInfo(p.Get("group_id").Int())
},
"get_group_member_list": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetGroupMemberList(p.Get("group_id").Int())
},
"get_group_member_info": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetGroupMemberInfo(
p.Get("group_id").Int(), p.Get("user_id").Int(),
p.Get("no_cache").Bool(),
)
},
"send_msg": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
if p.Get("group_id").Int() != 0 {
return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message").Str)
}
if p.Get("user_id").Int() != 0 {
return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("message").Str)
}
return coolq.MSG{}
},
"send_group_msg": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSendGroupMessage(p.Get("group_id").Int(), p.Get("message").Str)
},
"send_private_msg": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSendPrivateMessage(p.Get("user_id").Int(), p.Get("message").Str)
},
"delete_msg": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQDeleteMessage(int32(p.Get("message_id").Int()))
},
"set_friend_add_request": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
apr := true
if p.Get("approve").Exists() {
apr = p.Get("approve").Bool()
}
return bot.CQProcessFriendRequest(p.Get("flag").Str, apr)
},
"set_group_add_request": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
subType := p.Get("sub_type").Str
apr := true
if subType == "" {
subType = p.Get("type").Str
}
if p.Get("approve").Exists() {
apr = p.Get("approve").Bool()
}
return bot.CQProcessGroupRequest(p.Get("flag").Str, subType, apr)
},
"set_group_card": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupCard(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("card").Str)
},
"set_group_special_title": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupSpecialTitle(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("special_title").Str)
},
"set_group_kick": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupKick(p.Get("group_id").Int(), p.Get("user_id").Int(), p.Get("message").Str)
},
"set_group_ban": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupBan(p.Get("group_id").Int(), p.Get("user_id").Int(), uint32(p.Get("duration").Int()))
},
"set_group_whole_ban": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupWholeBan(p.Get("group_id").Int(), func() bool {
if p.Get("enable").Exists() {
return p.Get("enable").Bool()
}
return true
}())
},
"set_group_name": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQSetGroupName(p.Get("group_id").Int(), p.Get("name").Str)
},
"get_image": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetImage(p.Get("file").Str)
},
"get_group_msg": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetGroupMessage(int32(p.Get("message_id").Int()))
},
"can_send_image": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQCanSendImage()
},
"can_send_record": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQCanSendRecord()
},
"get_status": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetStatus()
},
"get_version_info": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetVersionInfo()
},
".handle_quick_operation": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQHandleQuickOperation(p.Get("context"), p.Get("operation"))
},
}