-
Notifications
You must be signed in to change notification settings - Fork 1
/
login.go
364 lines (349 loc) · 11.2 KB
/
login.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
package wwdk
import (
"bytes"
"encoding/json"
"encoding/xml"
"github.com/pkg/errors"
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/ikuiki/wwdk/conf"
"github.com/ikuiki/wwdk/datastruct"
"github.com/ikuiki/wwdk/tool"
)
// LoginChannelItem 登录时channel内返回的东西
type LoginChannelItem struct {
Err error
Code LoginStatus
Msg string
}
// LoginStatus 登录状态枚举
type LoginStatus int32
const (
// LoginStatusErrorOccurred 发生异常
LoginStatusErrorOccurred LoginStatus = -1
// LoginStatusWaitForScan 等待扫码
// 返回Msg: 待扫码url
LoginStatusWaitForScan LoginStatus = 1
// LoginStatusScanedWaitForLogin 用户已经扫码
// 返回Msg: 用户头像的base64
LoginStatusScanedWaitForLogin LoginStatus = 2
// LoginStatusScanedFinish 用户已同意登陆
LoginStatusScanedFinish LoginStatus = 3
// LoginStatusGotCookie 已获取到Cookie
LoginStatusGotCookie LoginStatus = 4
// LoginStatusInitFinish 登陆初始化完成
LoginStatusInitFinish LoginStatus = 5
// LoginStatusGotContact 已获取到联系人
LoginStatusGotContact LoginStatus = 6
// LoginStatusGotBatchContact 已获取到群聊成员
LoginStatusGotBatchContact LoginStatus = 7
)
func (wxwb *WechatWeb) getUUID(loginChannel chan<- LoginChannelItem) (uuid string) {
params := url.Values{}
params.Set("appid", conf.AppID)
params.Set("fun", "new")
params.Set("lang", conf.Lang)
params.Set("_", tool.GetWxTimeStamp())
req, _ := http.NewRequest("GET", "https://login.weixin.qq.com/jslogin?"+params.Encode(), nil)
resp, err := wxwb.request(req)
if err != nil {
panic(errors.New("request error: " + err.Error()))
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
ret := tool.ExtractWxWindowRespond(string(body))
if ret["window.QRLogin.code"] != "200" {
panic(errors.New("window.QRLogin.code = " + ret["window.QRLogin.code"]))
}
uuid = ret["window.QRLogin.uuid"]
loginChannel <- LoginChannelItem{
Code: LoginStatusWaitForScan,
Msg: "https://login.weixin.qq.com/l/" + uuid,
}
return uuid
}
// waitForScan 等待用户扫描二维码登陆
// 当扫码超时、扫码失败时,应当从getUUID方法重新开始
func (wxwb *WechatWeb) waitForScan(uuid string, loginChannel chan<- LoginChannelItem) (redirectURL string) {
var ret map[string]string
scaned := false
scaned2TipMap := map[bool]string{
false: "1",
true: "0",
}
for true {
redirectURL = func() (redirectURL string) {
params := url.Values{}
params.Set("tip", scaned2TipMap[scaned])
params.Set("uuid", uuid)
params.Set("_", tool.GetWxTimeStamp())
req, _ := http.NewRequest(`GET`, "https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?"+params.Encode(), nil)
resp, err := wxwb.request(req)
if err != nil {
wxwb.logger.Infof("waitForScan request error: %v\n", err)
return "" // return empty for continue
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
ret = tool.ExtractWxWindowRespond(string(body))
switch ret["window.code"] {
case "200": // 确认登陆
wxwb.logger.Info("Login success\n")
loginChannel <- LoginChannelItem{
Code: LoginStatusScanedFinish,
}
return ret["window.redirect_uri"]
case "201": // 用户已扫码
scaned = true
wxwb.logger.Info("Scan success, waiting for login\n")
loginChannel <- LoginChannelItem{
Code: LoginStatusScanedWaitForLogin,
Msg: ret["window.userAvatar"],
}
return "" // continue
case "400": // 登陆失败(二维码失效)
panic(errors.New("Login fail: qrcode has run out"))
case "408": // 等待登陆
time.Sleep(500 * time.Microsecond)
default:
panic(errors.New("Login fail: unknown response code: " + ret["window.code"]))
}
return
}()
if redirectURL != "" {
break
}
}
return redirectURL
}
func (wxwb *WechatWeb) getCookie(redirectURL string, loginChannel chan<- LoginChannelItem) {
req, _ := http.NewRequest(`GET`, redirectURL+"&fun=new", nil)
resp, err := wxwb.request(req)
if err != nil {
panic(errors.New("getCookie request error: " + err.Error()))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(errors.New("Read respond body error: " + err.Error()))
}
var bodyResp datastruct.GetCookieRespond
err = xml.Unmarshal(body, &bodyResp)
if err != nil {
panic(errors.New("Unmarshal respond xml error: " + err.Error()))
}
loginChannel <- LoginChannelItem{
Code: LoginStatusGotCookie,
}
// wxwb.refreshCookie(resp.Cookies()) // 在统一的Request方法已经调用了
wxwb.loginInfo.PassTicket = bodyResp.PassTicket
wxwb.loginInfo.sKey = bodyResp.Skey
}
func (wxwb *WechatWeb) wxInit(loginChannel chan<- LoginChannelItem) {
data, err := json.Marshal(datastruct.WxInitRequestBody{
BaseRequest: wxwb.baseRequest(),
})
if err != nil {
panic(errors.New("json.Marshal error: " + err.Error()))
}
params := url.Values{}
params.Set("pass_ticket", wxwb.loginInfo.PassTicket)
params.Set("skey", wxwb.loginInfo.sKey)
params.Set("r", tool.GetWxTimeStamp())
// resp, err := wxwb.apiRuntime.client.Post("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit?"+params.Encode(),
// "application/json;charset=UTF-8",
// bytes.NewReader(data))
req, err := http.NewRequest("POST",
"https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit?"+params.Encode(),
bytes.NewReader(data))
if err != nil {
panic(errors.New("create request error: " + err.Error()))
}
resp, err := wxwb.request(req)
if err != nil {
panic(errors.New("do request error: " + err.Error()))
}
defer resp.Body.Close()
respStruct := datastruct.WxInitRespond{}
body, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &respStruct)
if err != nil {
panic(errors.New("respond json Unmarshal to struct fail: " + err.Error()))
}
if respStruct.BaseResponse.Ret != 0 {
panic(errors.Errorf("respond ret error: %d", respStruct.BaseResponse.Ret))
}
loginChannel <- LoginChannelItem{
Code: LoginStatusInitFinish,
}
for _, contact := range respStruct.ContactList {
wxwb.contactList[contact.UserName] = contact
}
wxwb.userInfo.user = respStruct.User
wxwb.loginInfo.syncKey = respStruct.SyncKey
wxwb.loginInfo.sKey = respStruct.SKey
}
// 获取完整联系人
func (wxwb *WechatWeb) getContactList() (err error) {
params := url.Values{}
params.Set("r", tool.GetWxTimeStamp())
resp, err := wxwb.apiRuntime.client.Get("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?" + params.Encode())
if err != nil {
return errors.New("request error: " + err.Error())
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
respStruct := datastruct.GetContactRespond{}
err = json.Unmarshal(body, &respStruct)
if err != nil {
return errors.New("respond json Unmarshal to struct fail: " + err.Error())
}
if respStruct.BaseResponse.Ret != 0 {
return errors.Errorf("respond ret error: %d", respStruct.BaseResponse.Ret)
}
for _, contact := range respStruct.MemberList {
wxwb.contactList[contact.UserName] = contact
}
return nil
}
// 获取群聊的成员
func (wxwb *WechatWeb) getBatchContact() (err error) {
dataStruct := datastruct.GetBatchContactRequest{
BaseRequest: wxwb.baseRequest(),
}
for _, contact := range wxwb.contactList {
if contact.IsChatroom() {
dataStruct.List = append(dataStruct.List, datastruct.GetBatchContactRequestListItem{
UserName: contact.UserName,
})
}
}
dataStruct.Count = int64(len(dataStruct.List))
if dataStruct.Count == 0 {
return nil
}
data, err := json.Marshal(dataStruct)
if err != nil {
return errors.New("json.Marshal error: " + err.Error())
}
params := url.Values{}
params.Set("type", "ex")
params.Set("r", tool.GetWxTimeStamp())
resp, err := wxwb.apiRuntime.client.Post("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?"+params.Encode(),
"application/json;charset=UTF-8",
bytes.NewReader(data))
if err != nil {
return errors.New("request error: " + err.Error())
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
respStruct := datastruct.GetBatchContactResponse{}
err = json.Unmarshal(body, &respStruct)
if err != nil {
return errors.New("respond json Unmarshal to struct fail: " + err.Error())
}
if respStruct.BaseResponse.Ret != 0 {
return errors.Errorf("respond ret error: %d", respStruct.BaseResponse.Ret)
}
for _, contact := range respStruct.ContactList {
if c, ok := wxwb.contactList[contact.UserName]; ok {
c.MemberCount = contact.MemberCount
c.MemberList = contact.MemberList
c.EncryChatRoomID = contact.EncryChatRoomID
wxwb.contactList[c.UserName] = c
}
}
return
}
// Login 登陆方法总成
// param loginChannel 登陆状态channel,从中可以读取到登录情况
func (wxwb *WechatWeb) Login(loginChannel chan<- LoginChannelItem) {
// 尝试使用已存在的登录信息登录
go func() {
defer close(loginChannel)
defer func() {
if e := recover(); e != nil {
if err, ok := e.(error); ok {
// 发生了panic
loginChannel <- LoginChannelItem{
Code: LoginStatusErrorOccurred,
Err: err,
}
} else {
wxwb.logger.Errorf("WechatWeb.Login panic: \n%+v\n", e)
}
}
}()
// 尝试使用已存在的登录信息登录
logined := false
readed, _ := wxwb.readLoginInfo()
if readed {
wxwb.logger.Info("loaded stored login info")
if wxwb.getContactList() == nil {
// 获取联系人成功,则为已登陆状态
logined = true
wxwb.logger.Infof("reuse loginInfo [%s] logined at %v\n", wxwb.userInfo.user.NickName, wxwb.runInfo.LoginAt.Format("2006-01-02 15:04:05"))
}
}
if !logined {
if readed {
// 仅当成功读取了login信息并且登陆失败,才输出此log
wxwb.logger.Info("stored login info not avaliable\n")
}
wxwb.resetLoginInfo()
uuid := wxwb.getUUID(loginChannel)
redirectURL := wxwb.waitForScan(uuid, loginChannel)
// panic(redirectUrl)
wxwb.getCookie(redirectURL, loginChannel)
wxwb.wxInit(loginChannel)
err := wxwb.getContactList()
if err != nil {
loginChannel <- LoginChannelItem{
Code: LoginStatusErrorOccurred,
Err: err,
}
return
}
// 此处即认为登陆成功
wxwb.runInfo.LoginAt = time.Now()
}
loginChannel <- LoginChannelItem{
Code: LoginStatusGotContact,
}
// err = wxwb.StatusNotify(wxwb.userInfo.user.UserName, wxwb.userInfo.user.UserName, 3)
// if err != nil {
// return errors.New("StatusNotify error: " + err.Error())
// }
err := wxwb.getBatchContact()
if err != nil {
loginChannel <- LoginChannelItem{
Code: LoginStatusErrorOccurred,
Err: err,
}
return
}
loginChannel <- LoginChannelItem{
Code: LoginStatusGotBatchContact,
}
wxwb.logger.Infof("User %s has Login Success, total %d contacts\n", wxwb.userInfo.user.NickName, len(wxwb.contactList))
// 如有必要,记录login信息到storer
wxwb.writeLoginInfo()
}()
}
// Logout 退出登录
func (wxwb *WechatWeb) Logout() (err error) {
params := url.Values{}
params.Set("redirect", "0")
params.Set("type", "1")
params.Set("skey", wxwb.loginInfo.sKey)
form := url.Values{}
form.Set("sid", wxwb.loginInfo.cookie.Wxsid)
form.Set("uin", wxwb.loginInfo.cookie.Wxuin)
resp, err := wxwb.apiRuntime.client.PostForm("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxlogout?"+params.Encode(), form)
if err != nil {
return errors.New("request error: " + err.Error())
}
defer resp.Body.Close()
return nil
}