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
|
package binary
import (
"fmt"
pb "github.com/Rhymen/go-whatsapp/binary/proto"
"github.com/golang/protobuf/proto"
)
type Node struct {
Description string
Attributes map[string]string
Content interface{}
}
func Marshal(n Node) ([]byte, error) {
if n.Attributes != nil && n.Content != nil {
a, err := marshalMessageArray(n.Content.([]interface{}))
if err != nil {
return nil, err
}
n.Content = a
}
w := NewEncoder()
if err := w.WriteNode(n); err != nil {
return nil, err
}
return w.GetData(), nil
}
func marshalMessageArray(messages []interface{}) ([]Node, error) {
ret := make([]Node, len(messages))
for i, m := range messages {
if wmi, ok := m.(*pb.WebMessageInfo); ok {
b, err := marshalWebMessageInfo(wmi)
if err != nil {
return nil, nil
}
ret[i] = Node{"message", nil, b}
} else {
ret[i], ok = m.(Node)
if !ok {
return nil, fmt.Errorf("invalid Node")
}
}
}
return ret, nil
}
func marshalWebMessageInfo(p *pb.WebMessageInfo) ([]byte, error) {
b, err := proto.Marshal(p)
if err != nil {
return nil, err
}
return b, nil
}
func Unmarshal(data []byte) (*Node, error) {
r := NewDecoder(data)
n, err := r.ReadNode()
if err != nil {
return nil, err
}
if n != nil && n.Attributes != nil && n.Content != nil {
nContent, ok := n.Content.([]Node)
if ok {
n.Content, err = unmarshalMessageArray(nContent)
if err != nil {
return nil, err
}
}
}
return n, nil
}
func unmarshalMessageArray(messages []Node) ([]interface{}, error) {
ret := make([]interface{}, len(messages))
for i, msg := range messages {
if msg.Description == "message" {
info, err := unmarshalWebMessageInfo(msg.Content.([]byte))
if err != nil {
return nil, err
}
ret[i] = info
} else {
ret[i] = msg
}
}
return ret, nil
}
func unmarshalWebMessageInfo(msg []byte) (*pb.WebMessageInfo, error) {
message := &pb.WebMessageInfo{}
err := proto.Unmarshal(msg, message)
if err != nil {
return nil, err
}
return message, nil
}
|