forked from eatmoreapple/openwechat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
573 lines (521 loc) · 14 KB
/
user.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
package openwechat
import (
"bytes"
"errors"
"fmt"
"net/http"
"os"
"strings"
)
// 抽象的用户结构: 好友 群组 公众号
type User struct {
Uin int
HideInputBarFlag int
StarFriend int
Sex int
AppAccountFlag int
VerifyFlag int
ContactFlag int
WebWxPluginSwitch int
HeadImgFlag int
SnsFlag int
IsOwner int
MemberCount int
ChatRoomId int
UniFriend int
OwnerUin int
Statues int
AttrStatus int
Province string
City string
Alias string
DisplayName string
KeyWord string
EncryChatRoomId string
UserName string
NickName string
HeadImgUrl string
RemarkName string
PYInitial string
PYQuanPin string
RemarkPYInitial string
RemarkPYQuanPin string
Signature string
MemberList Members
Self *Self
}
// implement fmt.Stringer
func (u *User) String() string {
return fmt.Sprintf("<User:%s>", u.NickName)
}
// 获取用户头像
func (u *User) GetAvatarResponse() (*http.Response, error) {
return u.Self.Bot.Caller.Client.WebWxGetHeadImg(u.HeadImgUrl)
}
// 下载用户头像
func (u *User) SaveAvatar(filename string) error {
resp, err := u.GetAvatarResponse()
if err != nil {
return err
}
defer resp.Body.Close()
buffer := bytes.Buffer{}
if _, err := buffer.ReadFrom(resp.Body); err != nil {
return err
}
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(buffer.Bytes())
return err
}
// 获取用户的详情
func (u *User) Detail() (*User, error) {
if u.UserName == u.Self.UserName {
return u.Self.User, nil
}
members := Members{u}
request := u.Self.Bot.storage.Request
newMembers, err := u.Self.Bot.Caller.WebWxBatchGetContact(members, request)
if err != nil {
return nil, err
}
user := newMembers.First()
user.Self = u.Self
return user, nil
}
// 判断是否为好友
func (u *User) IsFriend() bool {
return !u.IsGroup() && strings.HasPrefix(u.UserName, "@") && u.VerifyFlag == 0
}
// 判断是否为群组
func (u *User) IsGroup() bool {
return strings.HasPrefix(u.UserName, "@@") && u.VerifyFlag == 0
}
// 判断是否为公众号
func (u *User) IsMP() bool {
return u.VerifyFlag == 8 || u.VerifyFlag == 24 || u.VerifyFlag == 136
}
// 自己,当前登录用户对象
type Self struct {
*User
Bot *Bot
fileHelper *Friend
members Members
friends Friends
groups Groups
mps Mps
}
// 获取所有的好友、群组、公众号信息
func (s *Self) Members(update ...bool) (Members, error) {
// 首先判断缓存里有没有,如果没有则去更新缓存
// 判断是否需要更新,如果传入的参数不为nil,则取第一个
if s.members == nil || (len(update) > 0 && update[0]) {
if err := s.updateMembers(); err != nil {
return nil, err
}
}
return s.members, nil
}
// 更新联系人处理
func (s *Self) updateMembers() error {
info := s.Bot.storage.LoginInfo
members, err := s.Bot.Caller.WebWxGetContact(info)
if err != nil {
return err
}
members.SetOwner(s)
s.members = members
return nil
}
// 获取文件传输助手对象,封装成Friend返回
// fh, err := self.FileHelper() // or fh := openwechat.NewFriendHelper(self)
func (s *Self) FileHelper() (*Friend, error) {
// 如果缓存里有,直接返回,否则去联系人里面找
if s.fileHelper != nil {
return s.fileHelper, nil
}
members, err := s.Members()
if err != nil {
return nil, err
}
users := members.SearchByUserName(1, "filehelper")
if users == nil {
s.fileHelper = NewFriendHelper(s)
} else {
s.fileHelper = &Friend{users.First()}
}
return s.fileHelper, nil
}
// 获取所有的好友
func (s *Self) Friends(update ...bool) (Friends, error) {
if s.friends == nil || (len(update) > 0 && update[0]) {
if _, err := s.Members(true); err != nil {
return nil, err
}
s.friends = s.members.Friends()
}
return s.friends, nil
}
// 获取所有的群组
func (s *Self) Groups(update ...bool) (Groups, error) {
if s.groups == nil || (len(update) > 0 && update[0]) {
if _, err := s.Members(true); err != nil {
return nil, err
}
s.groups = s.members.Groups()
}
return s.groups, nil
}
// 获取所有的公众号
func (s *Self) Mps(update ...bool) (Mps, error) {
if s.mps == nil || (len(update) > 0 && update[0]) {
if _, err := s.Members(true); err != nil {
return nil, err
}
s.mps = s.members.MPs()
}
return s.mps, nil
}
// 更新所有的联系人信息
func (s *Self) UpdateMembersDetail() error {
// 先获取所有的联系人
members, err := s.Members()
if err != nil {
return err
}
return members.detail(s)
}
// 抽象发送消息接口
func (s *Self) sendMessageToUser(user *User, msg *SendMessage) (*SentMessage, error) {
msg.FromUserName = s.UserName
msg.ToUserName = user.UserName
info := s.Bot.storage.LoginInfo
request := s.Bot.storage.Request
successSendMessage, err := s.Bot.Caller.WebWxSendMsg(msg, info, request)
if err != nil {
return nil, err
}
successSendMessage.Self = s
return successSendMessage, nil
}
// 发送消息给好友
func (s *Self) SendMessageToFriend(friend *Friend, msg *SendMessage) (*SentMessage, error) {
return s.sendMessageToUser(friend.User, msg)
}
// 发送文本消息给好友
func (s *Self) SendTextToFriend(friend *Friend, text string) (*SentMessage, error) {
msg := NewTextSendMessage(text, s.UserName, friend.UserName)
return s.SendMessageToFriend(friend, msg)
}
// 发送图片消息给好友
func (s *Self) SendImageToFriend(friend *Friend, file *os.File) (*SentMessage, error) {
req := s.Bot.storage.Request
info := s.Bot.storage.LoginInfo
return s.Bot.Caller.WebWxSendImageMsg(file, req, info, s.UserName, friend.UserName)
}
// 发送文件给好友
func (s *Self) SendFileToFriend(friend *Friend, file *os.File) (*SentMessage, error) {
req := s.Bot.storage.Request
info := s.Bot.storage.LoginInfo
return s.Bot.Caller.WebWxSendFile(file, req, info, s.UserName, friend.UserName)
}
// 设置好友备注
// self.SetRemarkNameToFriend(friend, "remark") // or friend.SetRemarkName("remark")
func (s *Self) SetRemarkNameToFriend(friend *Friend, remarkName string) error {
req := s.Bot.storage.Request
return s.Bot.Caller.WebWxOplog(req, remarkName, friend.UserName)
}
// 拉多名好友进群
// 最好自己是群主,成功率高一点,因为有的群允许非群组拉人,而有的群不允许
func (s *Self) AddFriendsIntoGroup(group *Group, friends ...*Friend) error {
if len(friends) == 0 {
return nil
}
// 获取群的所有的群员
groupMembers, err := group.Members()
if err != nil {
return err
}
// 判断当前的成员在不在群里面
for _, friend := range friends {
for _, member := range groupMembers {
if member.UserName == friend.UserName {
return fmt.Errorf("user %s has alreay in this group", friend.String())
}
}
}
req := s.Bot.storage.Request
info := s.Bot.storage.LoginInfo
return s.Bot.Caller.AddFriendIntoChatRoom(req, info, group, friends...)
}
// 从群聊中移除用户
// Deprecated
// 无论是网页版,还是程序上都不起作用
func (s *Self) RemoveMemberFromGroup(group *Group, members Members) error {
if len(members) == 0 {
return nil
}
if group.IsOwner == 0 {
return errors.New("group owner required")
}
groupMembers, err := group.Members()
if err != nil {
return err
}
// 判断用户是否在群聊中
var count int
for _, member := range members {
for _, gm := range groupMembers {
if gm.UserName == member.UserName {
count++
}
}
}
if count != len(members) {
return errors.New("invalid members")
}
req := s.Bot.storage.Request
info := s.Bot.storage.LoginInfo
return s.Bot.Caller.RemoveFriendFromChatRoom(req, info, group, members...)
}
// 拉好友进多个群聊
// AddFriendIntoGroups, 名字和上面的有点像
func (s *Self) AddFriendIntoManyGroups(friend *Friend, groups ...*Group) error {
for _, group := range groups {
if err := s.AddFriendsIntoGroup(group, friend); err != nil {
return err
}
}
return nil
}
// 发送消息给群组
func (s *Self) SendMessageToGroup(group *Group, msg *SendMessage) (*SentMessage, error) {
return s.sendMessageToUser(group.User, msg)
}
// 发送文本消息给群组
func (s *Self) SendTextToGroup(group *Group, text string) (*SentMessage, error) {
msg := NewTextSendMessage(text, s.UserName, group.UserName)
return s.SendMessageToGroup(group, msg)
}
// 发送图片消息给群组
func (s *Self) SendImageToGroup(group *Group, file *os.File) (*SentMessage, error) {
req := s.Bot.storage.Request
info := s.Bot.storage.LoginInfo
return s.Bot.Caller.WebWxSendImageMsg(file, req, info, s.UserName, group.UserName)
}
// 发送文件给群组
func (s *Self) SendFileToGroup(group *Group, file *os.File) (*SentMessage, error) {
req := s.Bot.storage.Request
info := s.Bot.storage.LoginInfo
return s.Bot.Caller.WebWxSendFile(file, req, info, s.UserName, group.UserName)
}
// 撤回消息
// sentMessage, err := friend.SendText("message")
// if err == nil {
// self.RevokeMessage(sentMessage) // or sentMessage.Revoke()
// }
func (s *Self) RevokeMessage(msg *SentMessage) error {
return s.Bot.Caller.WebWxRevokeMsg(msg, s.Bot.storage.Request)
}
// 转发消息接口
func (s *Self) forwardMessage(msg *SentMessage, users ...*User) error {
info := s.Bot.storage.LoginInfo
req := s.Bot.storage.Request
switch msg.Type {
case TextMessage:
for _, user := range users {
msg.FromUserName = s.UserName
msg.ToUserName = user.UserName
if _, err := s.Self.Bot.Caller.WebWxSendMsg(msg.SendMessage, info, req); err != nil {
return err
}
}
case ImageMessage:
for _, user := range users {
msg.FromUserName = s.UserName
msg.ToUserName = user.UserName
if _, err := s.Self.Bot.Caller.Client.WebWxSendMsgImg(msg.SendMessage, req, info); err != nil {
return err
}
}
case AppMessage:
for _, user := range users {
msg.FromUserName = s.UserName
msg.ToUserName = user.UserName
if _, err := s.Self.Bot.Caller.Client.WebWxSendAppMsg(msg.SendMessage, req); err != nil {
return err
}
}
}
return errors.New("unsupport message")
}
// 转发给好友
func (s *Self) ForwardMessageToFriends(msg *SentMessage, friends ...*Friend) error {
var users []*User
for _, friend := range friends {
users = append(users, friend.User)
}
return s.forwardMessage(msg, users...)
}
// 转发给群组
func (s *Self) ForwardMessageToGroups(msg *SentMessage, groups ...*Group) error {
var users []*User
for _, group := range groups {
users = append(users, group.User)
}
return s.forwardMessage(msg, users...)
}
// 抽象的用户组
type Members []*User
// 统计数量
func (m Members) Count() int {
return len(m)
}
// 获取第一个
func (m Members) First() *User {
if m.Count() > 0 {
u := m[0]
return u
}
return nil
}
// 获取最后一个
func (m Members) Last() *User {
if m.Count() > 0 {
u := m[m.Count()-1]
return u
}
return nil
}
// 设置owner
// 请不要随意设置
func (m Members) SetOwner(s *Self) {
for _, member := range m {
member.Self = s
}
}
// 根据用户名查找
func (m Members) SearchByUserName(limit int, username string) (results Members) {
return m.Search(limit, func(user *User) bool { return user.UserName == username })
}
// 根据昵称查找
func (m Members) SearchByNickName(limit int, nickName string) (results Members) {
return m.Search(limit, func(user *User) bool { return user.NickName == nickName })
}
// 根据备注查找
func (m Members) SearchByRemarkName(limit int, remarkName string) (results Members) {
return m.Search(limit, func(user *User) bool { return user.RemarkName == remarkName })
}
// 根据自定义条件查找
func (m Members) Search(limit int, condFuncList ...func(user *User) bool) (results Members) {
if condFuncList == nil {
return m
}
if limit <= 0 {
limit = m.Count()
}
for _, member := range m {
if count := len(results); count == limit {
break
}
var passCount int
for _, condFunc := range condFuncList {
if condFunc(member) {
passCount++
} else {
break
}
}
if passCount == len(condFuncList) {
results = append(results, member)
}
}
return
}
func (m Members) Friends() Friends {
friends := make(Friends, 0)
for _, mb := range m {
if mb.IsFriend() {
friend := &Friend{mb}
friends = append(friends, friend)
}
}
return friends
}
func (m Members) Groups() Groups {
groups := make(Groups, 0)
for _, mb := range m {
if mb.IsGroup() {
group := &Group{mb}
groups = append(groups, group)
}
}
return groups
}
func (m Members) MPs() Mps {
mps := make(Mps, 0)
for _, mb := range m {
if mb.IsMP() {
mp := &Mp{mb}
mps = append(mps, mp)
}
}
return mps
}
// 获取当前Members的详情
func (m Members) detail(self *Self) error {
// 获取他们的数量
members := m
count := members.Count()
// 一次更新50个,分情况讨论
// 获取总的需要更新的次数
var times int
if count < 50 {
times = 1
} else {
times = count / 50
}
var newMembers Members
request := self.Bot.storage.Request
var pMembers Members
// 分情况依次更新
for i := 1; i <= times; i++ {
if times == 1 {
pMembers = members
} else {
pMembers = members[(i-1)*50 : i*50]
}
nMembers, err := self.Bot.Caller.WebWxBatchGetContact(pMembers, request)
if err != nil {
return err
}
newMembers = append(newMembers, nMembers...)
}
// 最后判断是否全部更新完毕
total := times * 50
if total < count {
// 将全部剩余的更新完毕
left := count - total
pMembers = members[total : total+left]
nMembers, err := self.Bot.Caller.WebWxBatchGetContact(pMembers, request)
if err != nil {
return err
}
newMembers = append(newMembers, nMembers...)
}
if len(newMembers) > 0 {
newMembers.SetOwner(self)
self.members = newMembers
}
return nil
}
// 这里为了兼容Desktop版本找不到文件传输助手的问题
// 文件传输助手的微信身份标识符永远是filehelper
// 这种形式的对象可能缺少一些其他属性
// 但是不影响发送信息的功能
func NewFriendHelper(self *Self) *Friend {
return &Friend{&User{UserName: "filehelper", Self: self}}
}