-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathmessage.go
636 lines (577 loc) · 16.7 KB
/
message.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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
package message
// 部分借鉴 https://github.com/Mrs4s/MiraiGo/blob/master/message/message.go
import (
"encoding/xml"
"fmt"
"reflect"
"strconv"
"strings"
oidb2 "github.com/LagrangeDev/LagrangeGo/client/packets/pb/service/oidb"
"github.com/LagrangeDev/LagrangeGo/client/packets/pb/message"
"github.com/LagrangeDev/LagrangeGo/internal/proto"
"github.com/LagrangeDev/LagrangeGo/utils"
"github.com/LagrangeDev/LagrangeGo/utils/binary"
)
type IMessage interface {
GetElements() []IMessageElement
Chat() int64
ToString() string
Texts() []string
}
const (
Text ElementType = iota // 文本
Image // 图片
Face // 表情
At // 艾特
Reply // 回复
Service // 服务
Forward // 转发
File // 文件
Voice // 语音
Video // 视频
LightApp // 轻应用
RedBag // 红包
)
type (
PrivateMessage struct {
ID uint32
InternalID uint32
ClientSeq uint32
Self uint32
Target uint32
Time uint32
Sender *Sender
Elements []IMessageElement
}
TempMessage struct {
ID uint32
GroupUin uint32
GroupName string
Self uint32
Sender *Sender
Elements []IMessageElement
}
GroupMessage struct {
ID uint32
InternalID uint32
GroupUin uint32
GroupName string
Sender *Sender
Time uint32
Elements []IMessageElement
OriginalObject *message.PushMsgBody
}
SendingMessage struct {
Elements []IMessageElement
}
Sender struct {
Uin uint32
UID string
Nickname string
CardName string
AnonymousInfo *AnonymousInfo
IsFriend bool
}
AnonymousInfo struct {
AnonymousID string
AnonymousNick string
}
IMessageElement interface {
Type() ElementType
}
ElementType int
)
func (s *Sender) IsAnonymous() bool {
return s.Uin == 80000000
}
func ParsePrivateMessage(msg *message.PushMsgBody) *PrivateMessage {
prvMsg := &PrivateMessage{
ID: msg.ContentHead.Sequence.Unwrap(),
InternalID: msg.ContentHead.MsgId.Unwrap(),
Self: msg.ResponseHead.ToUin,
Target: msg.ResponseHead.FromUin,
Sender: &Sender{
Uin: msg.ResponseHead.FromUin,
UID: msg.ResponseHead.FromUid.Unwrap(),
IsFriend: true,
},
Time: msg.ContentHead.TimeStamp.Unwrap(),
Elements: ParseMessageElements(msg.Body.RichText.Elems),
}
if msg.Body != nil {
prvMsg.Elements = append(prvMsg.Elements, ParseMessageBody(msg.Body, false)...)
}
return prvMsg
}
func ParseGroupMessage(msg *message.PushMsgBody) *GroupMessage {
grpMsg := &GroupMessage{
ID: msg.ContentHead.Sequence.Unwrap(),
InternalID: msg.ContentHead.MsgId.Unwrap(),
GroupUin: msg.ResponseHead.Grp.GroupUin,
GroupName: msg.ResponseHead.Grp.GroupName,
Sender: &Sender{
Uin: msg.ResponseHead.FromUin,
UID: msg.ResponseHead.FromUid.Unwrap(),
Nickname: msg.ResponseHead.Grp.MemberName,
CardName: msg.ResponseHead.Grp.MemberName,
IsFriend: false,
},
Time: msg.ContentHead.TimeStamp.Unwrap(),
Elements: ParseMessageElements(msg.Body.RichText.Elems),
OriginalObject: msg,
}
if msg.Body != nil {
grpMsg.Elements = append(grpMsg.Elements, ParseMessageBody(msg.Body, true)...)
}
return grpMsg
}
func ParseTempMessage(msg *message.PushMsgBody) *TempMessage {
return &TempMessage{
Elements: ParseMessageElements(msg.Body.RichText.Elems),
}
}
func ParseMessageElements(msg []*message.Elem) []IMessageElement {
var res []IMessageElement
skipNext := false
for _, elem := range msg {
if skipNext {
skipNext = false
continue
}
if elem.SrcMsg != nil && len(elem.SrcMsg.OrigSeqs) != 0 {
r := &ReplyElement{
ReplySeq: elem.SrcMsg.OrigSeqs[0],
Time: uint32(elem.SrcMsg.Time.Unwrap()),
SenderUin: uint32(elem.SrcMsg.SenderUin),
GroupUin: uint32(elem.SrcMsg.ToUin.Unwrap()),
Elements: ParseMessageElements(elem.SrcMsg.Elems),
}
res = append(res, r)
}
if elem.Text != nil {
switch {
case len(elem.Text.Attr6Buf) > 0:
att6 := binary.NewReader(elem.Text.Attr6Buf)
att6.SkipBytes(7)
target := att6.ReadU32()
at := NewAt(target, elem.Text.Str.Unwrap())
at.SubType = AtTypeGroupMember
res = append(res, at)
default:
res = append(res, NewText(func() string {
if strings.Contains(elem.Text.Str.Unwrap(), "\r") && !strings.Contains(elem.Text.Str.Unwrap(), "\r\n") {
return strings.ReplaceAll(elem.Text.Str.Unwrap(), "\r", "\r\n")
}
return elem.Text.Str.Unwrap()
}()))
}
}
if elem.Face != nil {
switch {
case len(elem.Face.Old) > 0:
faceID := elem.Face.Index
if faceID.IsSome() {
res = append(res, &FaceElement{FaceID: uint32(faceID.Unwrap())})
}
case elem.CommonElem != nil && elem.CommonElem.ServiceType == 37 && elem.CommonElem.PbElem != nil:
qFace := message.QFaceExtra{}
if err := proto.Unmarshal(elem.CommonElem.PbElem, &qFace); err == nil {
if qFace.Qsid.IsSome() {
res = append(res, &FaceElement{FaceID: uint32(qFace.Qsid.Unwrap()), isLargeFace: true})
}
}
case elem.CommonElem != nil && elem.CommonElem.ServiceType == 33 && elem.CommonElem.PbElem != nil:
qFace := message.QSmallFaceExtra{}
err := proto.Unmarshal(elem.CommonElem.PbElem, &qFace)
if err == nil {
res = append(res, &FaceElement{FaceID: qFace.FaceId, isLargeFace: false})
}
}
}
if elem.VideoFile != nil {
return []IMessageElement{
&ShortVideoElement{
Name: elem.VideoFile.FileName,
UUID: elem.VideoFile.FileUuid,
Size: uint32(elem.VideoFile.FileSize),
Md5: elem.VideoFile.FileMd5,
Thumb: &VideoThumb{
Size: uint32(elem.VideoFile.ThumbFileSize),
Md5: elem.VideoFile.ThumbFileMd5,
},
},
}
}
if elem.CustomFace != nil {
if len(elem.CustomFace.Md5) == 0 {
continue
}
var url string
if strings.Contains(elem.CustomFace.OrigUrl, "rkey") {
url = "https://multimedia.nt.qq.com.cn" + elem.CustomFace.OrigUrl
} else {
url = "http://gchat.qpic.cn" + elem.CustomFace.OrigUrl
}
res = append(res, func() *ImageElement {
img := &ImageElement{
ImageID: elem.CustomFace.FilePath,
Size: elem.CustomFace.Size,
Width: uint32(elem.CustomFace.Width),
Height: uint32(elem.CustomFace.Height),
URL: url,
Md5: elem.CustomFace.Md5,
}
if elem.CustomFace.PbRes != nil {
img.SubType = elem.CustomFace.PbRes.SubType
img.Summary = elem.CustomFace.PbRes.Summary
}
return img
}())
}
if elem.NotOnlineImage != nil {
if len(elem.NotOnlineImage.PicMd5) == 0 {
continue
}
var url string
if strings.Contains(elem.NotOnlineImage.OrigUrl, "rkey") {
url = "https://multimedia.nt.qq.com.cn" + elem.NotOnlineImage.OrigUrl
} else {
url = "http://gchat.qpic.cn" + elem.NotOnlineImage.OrigUrl
}
img := &ImageElement{
ImageID: elem.NotOnlineImage.FilePath,
Size: elem.NotOnlineImage.FileLen,
Width: elem.NotOnlineImage.PicWidth,
Height: elem.NotOnlineImage.PicHeight,
URL: url,
Md5: elem.NotOnlineImage.PicMd5,
}
if elem.NotOnlineImage.PbRes != nil {
img.SubType = elem.NotOnlineImage.PbRes.SubType
img.Summary = elem.NotOnlineImage.PbRes.Summary
}
res = append(res, img)
}
// new protocol image
if elem.CommonElem != nil {
switch elem.CommonElem.ServiceType {
case 48:
extra := &oidb2.MsgInfo{}
err := proto.Unmarshal(elem.CommonElem.PbElem, extra)
if err != nil {
continue
}
index := extra.MsgInfoBody[0].Index
switch elem.CommonElem.BusinessType {
case 10, 20: // img
res = append(res, &ImageElement{
ImageID: index.Info.FileName,
FileUUID: index.FileUuid,
SubType: int32(extra.ExtBizInfo.Pic.BizType),
Summary: utils.Ternary(extra.ExtBizInfo.Pic.TextSummary == "", "[图片]", extra.ExtBizInfo.Pic.TextSummary),
Md5: utils.MustParseHexStr(index.Info.FileHash),
Sha1: utils.MustParseHexStr(index.Info.FileSha1),
Width: index.Info.Width,
Height: index.Info.Height,
Size: index.Info.FileSize,
MsgInfo: extra,
})
case 12, 22: // record 22 for Group
res = append(res, &VoiceElement{
Name: index.Info.FileName,
UUID: index.FileUuid,
Md5: utils.MustParseHexStr(index.Info.FileHash),
Sha1: utils.MustParseHexStr(index.Info.FileSha1),
Duration: index.Info.Time,
Node: index,
})
}
case 3: // 闪照
img := message.NotOnlineImage{}
reader := binary.NewReader(elem.CommonElem.PbElem[1:])
length, _ := reader.ReadUvarint()
err := proto.Unmarshal(reader.ReadBytes(int(length)), &img)
if err != nil {
continue
}
res = append(res, &ImageElement{
ImageID: img.FilePath,
Md5: img.PicMd5,
Size: img.FileLen,
SubType: img.PbRes.SubType,
Flash: true,
Summary: "[闪照]",
Width: img.PicWidth,
Height: img.PicHeight,
URL: fmt.Sprintf("http://gchat.qpic.cn/gchatpic_new/0/0-0-%X/0", img.PicMd5),
})
skipNext = true
case 33:
var newSysFaceMsg message.QSmallFaceExtra
_ = proto.Unmarshal(elem.CommonElem.PbElem, &newSysFaceMsg)
res = append(res, NewFace(newSysFaceMsg.FaceId))
case 37:
var faceExtra message.QFaceExtra
_ = proto.Unmarshal(elem.CommonElem.PbElem, &faceExtra)
result, _ := strconv.ParseInt(faceExtra.ResultId.Unwrap(), 10, 32)
res = append(res, &FaceElement{
FaceID: uint32(faceExtra.Qsid.Unwrap()),
ResultID: uint32(result),
isLargeFace: true,
}) // sticker 永远为单独消息
skipNext = true
}
}
if elem.TransElem != nil && elem.TransElem.ElemType == 24 {
payload := binary.NewReader(elem.TransElem.ElemValue)
payload.SkipBytes(1)
data := payload.ReadBytesWithLength("u16", false)
extra := message.GroupFileExtra{}
if err := proto.Unmarshal(data, &extra); err != nil {
continue
}
res = append(res, &FileElement{
FileSize: extra.Inner.Info.FileSize,
FileMd5: []byte(extra.Inner.Info.FileMd5),
FileID: extra.Inner.Info.FileId,
FileName: extra.Inner.Info.FileName,
})
}
if elem.RichMsg != nil && elem.RichMsg.ServiceId.Unwrap() == 35 {
if elem.RichMsg.Template1 != nil {
xmlData := binary.ZlibUncompress(elem.RichMsg.Template1[1:])
multimsg := MultiMessage{}
if err := xml.Unmarshal(xmlData, &multimsg); err == nil {
res = append(res, NewForwardWithResID(multimsg.ResID))
} else {
res = append(res, &XMLElement{
ServiceID: 35,
Content: utils.B2S(binary.ZlibUncompress(elem.RichMsg.Template1[1:])),
})
}
}
}
if elem.LightAppElem != nil && len(elem.LightAppElem.Data) > 1 {
var content []byte
if elem.LightAppElem.Data[0] == 0 {
content = elem.LightAppElem.Data[1:]
}
if elem.LightAppElem.Data[0] == 1 {
content = binary.ZlibUncompress(elem.LightAppElem.Data[1:])
}
if len(content) > 0 && len(content) < 1024*1024*1024 { // 解析出错 or 非法内容
res = append(res, NewLightApp(utils.B2S(content)))
}
}
}
return res
}
func ParseMessageBody(body *message.MessageBody, isGroup bool) []IMessageElement {
var res []IMessageElement
if body != nil {
if body.RichText != nil && body.RichText.Ptt != nil {
ptt := body.RichText.Ptt
switch {
case isGroup && ptt.FileId != 0:
res = append(res, &VoiceElement{
Name: ptt.FileName,
UUID: ptt.FileUuid,
Md5: ptt.FileMd5,
Node: &oidb2.IndexNode{
FileUuid: ptt.GroupFileKey,
},
})
case !isGroup:
res = append(res, &VoiceElement{
Name: ptt.FileName,
UUID: ptt.FileUuid,
Md5: ptt.FileMd5,
Node: &oidb2.IndexNode{
FileUuid: ptt.FileUuid,
},
})
}
}
if body.MsgContent != nil {
extra := message.FileExtra{}
if err := proto.Unmarshal(body.MsgContent, &extra); err != nil {
return res
}
if extra.File.FileSize.IsSome() && extra.File.FileName.IsSome() && extra.File.FileMd5 != nil && extra.File.FileUuid.IsSome() && extra.File.FileHash.IsSome() {
res = append(res, &FileElement{
FileSize: uint64(extra.File.FileSize.Unwrap()),
FileName: extra.File.FileName.Unwrap(),
FileMd5: extra.File.FileMd5,
FileUUID: extra.File.FileUuid.Unwrap(),
FileHash: extra.File.FileHash.Unwrap(),
})
}
}
}
return res
}
func (msg *GroupMessage) ToString() string {
//var strBuilder strings.Builder
//for _, elem := range msg.Elements {
// switch e := elem.(type) {
// case *TextElement:
// strBuilder.WriteString(e.Content)
// case *ImageElement:
// strBuilder.WriteString("[Image: ")
// strBuilder.WriteString(e.ImageID)
// strBuilder.WriteString("]")
// case *AtElement:
// strBuilder.WriteString(e.Display)
// case *ReplyElement:
// strBuilder.WriteString("[Reply: ")
// strBuilder.WriteString(strconv.FormatInt(int64(e.ReplySeq), 10))
// strBuilder.WriteString("]")
// case *FaceElement:
// strBuilder.WriteString("[Face: ")
// strBuilder.WriteString(strconv.FormatInt(int64(e.FaceID), 10))
// if e.isLargeFace {
// strBuilder.WriteString(", isLargeFace: true]")
// }
// strBuilder.WriteString("]")
// case *VoiceElement:
// strBuilder.WriteString("[Record: ")
// strBuilder.WriteString(e.Name)
// strBuilder.WriteString("]")
// }
//}
//return strBuilder.String()
return ToReadableString(msg.Elements)
}
func (msg *GroupMessage) GetElements() []IMessageElement {
return msg.Elements
}
func (msg *GroupMessage) Chat() int64 {
return int64(msg.ID)
}
func (msg *GroupMessage) Texts() []string {
texts := make([]string, 0, len(msg.Elements))
for _, elem := range msg.Elements {
texts = append(texts, ToReadableStringEle(elem))
}
return texts
}
func (msg *PrivateMessage) ToString() string {
return ToReadableString(msg.Elements)
}
func (msg *PrivateMessage) GetElements() []IMessageElement {
return msg.Elements
}
func (msg *PrivateMessage) Chat() int64 {
return int64(msg.ID)
}
func (msg *PrivateMessage) Texts() []string {
texts := make([]string, 0, len(msg.Elements))
for _, elem := range msg.Elements {
texts = append(texts, ToReadableStringEle(elem))
}
return texts
}
func (msg *TempMessage) ToString() string {
return ToReadableString(msg.Elements)
}
func (msg *TempMessage) GetElements() []IMessageElement {
return msg.Elements
}
func (msg *TempMessage) Chat() int64 {
return int64(msg.ID)
}
func (msg *TempMessage) Texts() []string {
texts := make([]string, 0, len(msg.Elements))
for _, elem := range msg.Elements {
texts = append(texts, ToReadableStringEle(elem))
}
return texts
}
func ToReadableString(m []IMessageElement) string {
sb := new(strings.Builder)
for _, elem := range m {
sb.WriteString(ToReadableStringEle(elem))
}
return sb.String()
}
func ToReadableStringEle(elem IMessageElement) string {
switch e := elem.(type) {
case *TextElement:
return e.Content
case *ImageElement:
return "[图片]"
case *AtElement:
return e.Display
case *ReplyElement:
return "[回复]" // [Optional] + ToReadableString(e.Elements), 这里不破坏原义不添加
case *FaceElement:
return "[表情]"
case *VoiceElement:
return "[语音]"
case *ShortVideoElement:
return "[视频]"
case *LightAppElement:
return "[卡片消息]"
case *ForwardMessage:
return "[转发消息]"
default:
return "[暂不支持该消息类型]"
}
}
func NewSendingMessage() *SendingMessage {
return &SendingMessage{}
}
func (msg *SendingMessage) GetElems() []IMessageElement {
return msg.Elements
}
// Append 要传入msg的引用
func (msg *SendingMessage) Append(e IMessageElement) *SendingMessage {
v := reflect.ValueOf(e)
if v.Kind() == reflect.Ptr && !v.IsNil() {
msg.Elements = append(msg.Elements, e)
}
return msg
}
func (msg *SendingMessage) FirstOrNil(f func(element IMessageElement) bool) IMessageElement {
for _, elem := range msg.Elements {
if f(elem) {
return elem
}
}
return nil
}
func ElementsHasType(elems []IMessageElement, t ElementType) bool {
for _, elem := range elems {
if elem.Type() == t {
return true
}
}
return false
}
func PackElementsToBody(msgElems []IMessageElement) (msgBody *message.MessageBody) {
msgBody = &message.MessageBody{
RichText: &message.RichText{Elems: PackElements(msgElems)},
}
for _, elem := range msgElems {
bd, ok := elem.(MsgContentBuilder)
if !ok {
continue
}
msgBody.MsgContent = bd.BuildContent()
}
return
}
func PackElements(msgElems []IMessageElement) []*message.Elem {
if len(msgElems) == 0 {
return nil
}
elems := make([]*message.Elem, 0, len(msgElems))
for _, elem := range msgElems {
bd, ok := elem.(ElementBuilder)
if !ok {
continue
}
elems = append(elems, bd.BuildElement()...)
}
return elems
}