-
Notifications
You must be signed in to change notification settings - Fork 1
/
builder.go
336 lines (304 loc) · 8.91 KB
/
builder.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
// Copyright 2020 The jackal Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package stravaganza
import (
"errors"
"fmt"
"github.com/golang/protobuf/proto"
)
// Builder builds generic XML node elements.
type Builder struct {
attrs []*PBAttribute
elements []*PBElement
name, text string
validateJIDs bool
}
// NewBuilder returns a name initialized builder instance.
func NewBuilder(name string) *Builder {
return &Builder{name: name}
}
// NewMessageBuilder returns a 'message' stanza builder instance.
func NewMessageBuilder() *Builder {
return NewBuilder("message")
}
// NewPresenceBuilder returns a 'presence' stanza builder instance.
func NewPresenceBuilder() *Builder {
return NewBuilder("presence")
}
// NewIQBuilder returns an 'iq' stanza builder instance.
func NewIQBuilder() *Builder {
return NewBuilder("iq")
}
// NewBuilderFromElement returns an element builder derived from a copied element.
func NewBuilderFromElement(element Element) *Builder {
if element == nil {
return &Builder{}
}
protoFrom := element.Proto()
return &Builder{
name: protoFrom.GetName(),
text: protoFrom.GetText(),
attrs: copyProtoAttributes(protoFrom.GetAttributes()),
elements: protoFrom.GetElements(),
}
}
// NewBuilderFromBinary returns an element builder derived from an element binary representation.
func NewBuilderFromBinary(b []byte) (*Builder, error) {
var protoFrom PBElement
if err := proto.Unmarshal(b, &protoFrom); err != nil {
return nil, err
}
return &Builder{
name: protoFrom.GetName(),
text: protoFrom.GetText(),
attrs: protoFrom.GetAttributes(),
elements: protoFrom.GetElements(),
}, nil
}
// NewBuilderFromProto returns an element builder derived from proto type.
func NewBuilderFromProto(protoFrom *PBElement) *Builder {
return &Builder{
name: protoFrom.GetName(),
text: protoFrom.GetText(),
attrs: protoFrom.GetAttributes(),
elements: protoFrom.GetElements(),
}
}
// WithName sets XML node name.
func (b *Builder) WithName(name string) *Builder {
b.name = name
return b
}
// WithAttribute sets an XML node attribute (label=value).
func (b *Builder) WithAttribute(label, value string) *Builder {
for i, pbAttr := range b.attrs {
if pbAttr.Label == label {
b.attrs[i].Value = value
return b
}
}
b.attrs = append(b.attrs, &PBAttribute{Label: label, Value: value})
return b
}
// WithAttributes sets all XML node attributes.
func (b *Builder) WithAttributes(attributes ...Attribute) *Builder {
for _, attr := range attributes {
b.WithAttribute(attr.Label, attr.Value)
}
return b
}
// WithoutAttribute removes an XML node attribute.
func (b *Builder) WithoutAttribute(label string) *Builder {
for i, pbAttr := range b.attrs {
if pbAttr.Label == label {
b.attrs = append(b.attrs[:i], b.attrs[i+1:]...)
return b
}
}
return b
}
// WithChild appends a new sub element.
func (b *Builder) WithChild(child Element) *Builder {
b.elements = append(b.elements, child.Proto())
return b
}
// WithChildren appends all new sub elements.
func (b *Builder) WithChildren(children ...Element) *Builder {
for _, child := range children {
b.elements = append(b.elements, child.Proto())
}
return b
}
// WithoutChildren removes all elements with a given name.
func (b *Builder) WithoutChildren(name string) *Builder {
filtered := b.elements[:0]
for _, pbElem := range b.elements {
if pbElem.Name != name {
filtered = append(filtered, pbElem)
}
}
b.elements = filtered
return b
}
// WithoutChildrenNamespace removes all elements with a given name and namespace.
func (b *Builder) WithoutChildrenNamespace(name, ns string) *Builder {
filtered := b.elements[:0]
for _, pbElem := range b.elements {
if pbElem.Name != name || getProtoElementAttribute(pbElem, xmlNamespace) != ns {
filtered = append(filtered, pbElem)
}
}
b.elements = filtered
return b
}
// WithText sets XML node text value.
func (b *Builder) WithText(text string) *Builder {
b.text = text
return b
}
// WithValidateJIDs sets validate JIDs value.
func (b *Builder) WithValidateJIDs(validateJIDs bool) *Builder {
b.validateJIDs = validateJIDs
return b
}
// Build returns a new element instance.
func (b *Builder) Build() Element {
return &element{pb: b.buildProtoElement()}
}
// BuildStanza validates and returns a generic stanza instance.
func (b *Builder) BuildStanza() (Stanza, error) {
pbElem := b.buildProtoElement()
s := &stanza{
element: element{pb: pbElem},
}
// validate 'to' and 'from' JIDs...
if err := s.setFromAndToJIDs(b.validateJIDs); err != nil {
return nil, err
}
return s, nil
}
// BuildIQ validates and returns a new IQ stanza.
func (b *Builder) BuildIQ() (*IQ, error) {
if b.name != "iq" {
return nil, fmt.Errorf("stravaganza: wrong iq element name: %s", b.name)
}
pbElem := b.buildProtoElement()
if len(getProtoElementAttribute(pbElem, "id")) == 0 {
return nil, errors.New(`stravaganza: iq "id" attribute is required`)
}
iqType := getProtoElementAttribute(pbElem, "type")
if len(iqType) == 0 {
return nil, errors.New(`stravaganza: iq "type" attribute is required`)
}
if !isIQType(iqType) {
return nil, fmt.Errorf(`stravaganza: invalid iq "type" attribute: %s`, iqType)
}
elemCount := len(pbElem.Elements)
if (iqType == GetType || iqType == SetType) && elemCount != 1 {
return nil, errors.New(`stravaganza: an iq stanza of type "get" or "set" must contain one and only one child element`)
}
if iqType == ResultType && elemCount > 1 {
return nil, errors.New(`stravaganza: an iq stanza of type "result" must include zero or one child elements`)
}
iq := &IQ{
stanza: stanza{
element: element{pb: pbElem},
},
}
// validate 'to' and 'from' JIDs...
if err := iq.setFromAndToJIDs(b.validateJIDs); err != nil {
return nil, err
}
return iq, nil
}
// BuildMessage validates and returns a new Message stanza.
func (b *Builder) BuildMessage() (*Message, error) {
if b.name != "message" {
return nil, fmt.Errorf(`stravaganza: wrong message element name: %s`, b.name)
}
pbElem := b.buildProtoElement()
messageType := getProtoElementAttribute(pbElem, "type")
if !isMessageType(messageType) {
return nil, fmt.Errorf(`stravaganza: invalid message "type" attribute: %s`, messageType)
}
m := &Message{
stanza: stanza{
element: element{pb: pbElem},
},
}
// validate 'to' and 'from' JIDs...
if err := m.setFromAndToJIDs(b.validateJIDs); err != nil {
return nil, err
}
return m, nil
}
// BuildPresence validates and returns a new Presence stanza.
func (b *Builder) BuildPresence() (*Presence, error) {
if b.name != "presence" {
return nil, fmt.Errorf("stravaganza: wrong presence element name: %s", b.name)
}
pbElem := b.buildProtoElement()
presenceType := getProtoElementAttribute(pbElem, "type")
if !isPresenceType(presenceType) {
return nil, fmt.Errorf(`stravaganza: invalid presence "type" attribute: %s`, presenceType)
}
p := &Presence{
stanza: stanza{
element: element{pb: pbElem},
},
}
// validate 'to' and 'from' JIDs...
if err := p.setFromAndToJIDs(b.validateJIDs); err != nil {
return nil, err
}
// validate presence status...
if err := p.validateStatus(); err != nil {
return nil, err
}
// set show and priority values...
if err := p.setShow(); err != nil {
return nil, err
}
if err := p.setPriority(); err != nil {
return nil, err
}
return p, nil
}
// EmptyElement returns an empty element instace.
// Useful in case you want to deserialize an element using encoding.UnmarshalBinary interface.
func EmptyElement() Element {
return &element{pb: &PBElement{}}
}
func (b *Builder) buildProtoElement() *PBElement {
return &PBElement{
Name: b.name,
Attributes: b.attrs,
Elements: b.elements,
Text: b.text,
}
}
func copyProtoAttributes(pbAttrs []*PBAttribute) []*PBAttribute {
cp := make([]*PBAttribute, len(pbAttrs))
for i, pbAttr := range pbAttrs {
var cpAttr PBAttribute
cpAttr.Label = pbAttr.Label
cpAttr.Value = pbAttr.Value
cp[i] = &cpAttr
}
return cp
}
func isIQType(tp string) bool {
switch tp {
case ErrorType, GetType, SetType, ResultType:
return true
}
return false
}
func isMessageType(messageType string) bool {
switch messageType {
case "", ErrorType, NormalType, HeadlineType, ChatType, GroupChatType:
return true
default:
return false
}
}
func isPresenceType(presenceType string) bool {
switch presenceType {
case ErrorType, AvailableType, UnavailableType, SubscribeType,
UnsubscribeType, SubscribedType, UnsubscribedType, ProbeType:
return true
default:
return false
}
}