-
Notifications
You must be signed in to change notification settings - Fork 0
/
pep.go
1254 lines (1132 loc) · 36.6 KB
/
pep.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package xep0163
import (
"context"
"crypto/sha256"
"fmt"
"github.com/dantin/cubit/log"
"github.com/dantin/cubit/module/xep0004"
"github.com/dantin/cubit/module/xep0030"
"github.com/dantin/cubit/module/xep0115"
"github.com/dantin/cubit/router"
"github.com/dantin/cubit/storage/repository"
"github.com/dantin/cubit/util/runqueue"
"github.com/dantin/cubit/xmpp"
"github.com/dantin/cubit/xmpp/jid"
"github.com/google/uuid"
pubsubmodel "github.com/dantin/cubit/model/pubsub"
rostermodel "github.com/dantin/cubit/model/roster"
)
const (
pubSubNamespace = "http://jabber.org/protocol/pubsub"
pubSubOwnerNamespace = "http://jabber.org/protocol/pubsub#owner"
pubSubEventNamespace = "http://jabber.org/protocol/pubsub#event"
pubSubErrorNamespace = "http://jabber.org/protocol/pubsub#errors"
)
var defaultNodeOptions = pubsubmodel.Options{
DeliverNotifications: true,
DeliverPayloads: true,
PersistItems: true,
AccessModel: pubsubmodel.Presence,
MaxItems: 1,
SendLastPublishedItem: pubsubmodel.OnSubAndPresence,
NotificationType: xmpp.HeadlineType,
}
type commandOptions struct {
allowedAffiliations []string
includeAffiliations bool
includeSubscriptions bool
checkAccess bool
failOnNotFound bool
}
type commandContext struct {
host string
nodeID string
isAccountOwner bool
node *pubsubmodel.Node
affiliations []pubsubmodel.Affiliation
subscriptions []pubsubmodel.Subscription
accessChecker *accessChecker
}
// Pep represents a Personal Eventing Protocol module.
type Pep struct {
runQueue *runqueue.RunQueue
router router.Router
rosterRep repository.Roster
pubSubRep repository.PubSub
disco *xep0030.DiscoInfo
entityCaps *xep0115.EntityCaps
hosts []string
}
// New returns a PEP command IQ handler module.
func New(disco *xep0030.DiscoInfo, presenceHub *xep0115.EntityCaps, router router.Router, rosterRep repository.Roster, pubSubRep repository.PubSub) *Pep {
p := &Pep{
runQueue: runqueue.New("xep0163"),
rosterRep: rosterRep,
pubSubRep: pubSubRep,
router: router,
disco: disco,
entityCaps: presenceHub,
}
// register account identity and features
if disco != nil {
for _, feature := range pepFeatures {
disco.RegisterAccountFeature(feature)
}
}
// register disco items
p.registerDiscoItems(context.Background())
return p
}
// MatchesIQ returns whether or not an IQ should be processed by the PEP module.
func (x *Pep) MatchesIQ(iq *xmpp.IQ) bool {
pubSub := iq.Elements().Child("pubsub")
if pubSub == nil {
return false
}
switch pubSub.Namespace() {
case pubSubNamespace, pubSubOwnerNamespace:
return true
}
return false
}
// ProcessIQ processes a version IQ taking according actions over the associated stream
func (x *Pep) ProcessIQ(ctx context.Context, iq *xmpp.IQ) {
x.runQueue.Run(func() {
x.processIQ(ctx, iq)
})
}
// SubscribeToAll subscribes a jid to all host nodes
func (x *Pep) SubscribeToAll(ctx context.Context, host string, jid *jid.JID) {
x.runQueue.Run(func() {
if err := x.subscribeToAll(ctx, host, jid); err != nil {
log.Error(err)
}
})
}
// UnsubscribeFromAll unsubscribes a jid from all host nodes
func (x *Pep) UnsubscribeFromAll(ctx context.Context, host string, jid *jid.JID) {
x.runQueue.Run(func() {
if err := x.unsubscribeFromAll(ctx, host, jid); err != nil {
log.Error(err)
}
})
}
// DeliverLastItems delivers last items from all those nodes to which the jid is subscribed
func (x *Pep) DeliverLastItems(ctx context.Context, jid *jid.JID) {
x.runQueue.Run(func() {
if err := x.deliverLastItems(ctx, jid); err != nil {
log.Error(err)
}
})
}
// Shutdown shuts down version module.
func (x *Pep) Shutdown() error {
c := make(chan struct{})
x.runQueue.Stop(func() { close(c) })
<-c
return nil
}
func (x *Pep) processIQ(ctx context.Context, iq *xmpp.IQ) {
pubSub := iq.Elements().Child("pubsub")
switch pubSub.Namespace() {
case pubSubNamespace:
x.processRequest(ctx, iq, pubSub)
case pubSubOwnerNamespace:
x.processOwnerRequest(ctx, iq, pubSub)
}
}
func (x *Pep) registerDiscoItems(ctx context.Context) {
if x.disco == nil {
return // nothing to do here
}
if err := x.registerDiscoItemHandlers(ctx); err != nil {
log.Warnf("pep: failed to register disco item handlers: %v", err)
}
}
func (x *Pep) registerDiscoItemHandlers(ctx context.Context) error {
// unregister previous handlers
for _, h := range x.hosts {
x.disco.UnregisterProvider(h)
}
// register current ones
hosts, err := x.pubSubRep.FetchHosts(ctx)
if err != nil {
return err
}
for _, host := range hosts {
x.disco.RegisterProvider(host, &discoInfoProvider{
rosterRep: x.rosterRep,
pubSubRep: x.pubSubRep,
})
}
x.hosts = hosts
return nil
}
func (x *Pep) subscribeToAll(ctx context.Context, host string, subJID *jid.JID) error {
nodes, err := x.pubSubRep.FetchNodes(ctx, host)
if err != nil {
return err
}
for _, node := range nodes {
if err := x.subscribeTo(ctx, &node, subJID); err != nil {
return err
}
}
return nil
}
func (x *Pep) subscribeTo(ctx context.Context, n *pubsubmodel.Node, subJID *jid.JID) error {
// upsert subscription
subID := subscriptionID(subJID.ToBareJID().String(), n.Host, n.Name)
sub := pubsubmodel.Subscription{
SubID: subID,
JID: subJID.ToBareJID().String(),
Subscription: pubsubmodel.Subscribed,
}
if err := x.pubSubRep.UpsertNodeSubscription(ctx, &sub, n.Host, n.Name); err != nil {
return err
}
log.Infof("pep: subscription created (host: %s, node_id: %s, jid: %s)", n.Host, n.Name, subJID)
// notify subscription update
affiliations, err := x.pubSubRep.FetchNodeAffiliations(ctx, n.Host, n.Name)
if err != nil {
return err
}
subscriptionElem := xmpp.NewElementName("subscription")
subscriptionElem.SetAttribute("node", n.Name)
subscriptionElem.SetAttribute("jid", subJID.ToBareJID().String())
subscriptionElem.SetAttribute("subid", subID)
subscriptionElem.SetAttribute("subscription", pubsubmodel.Subscribed)
if n.Options.DeliverNotifications && n.Options.NotifySub {
x.notifyOwners(ctx, subscriptionElem, affiliations, n.Host, n.Options.NotificationType)
}
// send last node item
switch n.Options.SendLastPublishedItem {
case pubsubmodel.OnSub, pubsubmodel.OnSubAndPresence:
var subAff *pubsubmodel.Affiliation
for _, aff := range affiliations {
if aff.JID == subJID.ToBareJID().String() {
subAff = &aff
break
}
}
accessChecker := &accessChecker{
host: n.Host,
nodeID: n.Name,
accessModel: n.Options.AccessModel,
rosterAllowedGroups: n.Options.RosterGroupsAllowed,
affiliation: subAff,
rosterRep: x.rosterRep,
}
return x.sendLastPublishedItem(ctx, subJID, accessChecker, n.Host, n.Name, n.Options.NotificationType)
}
return nil
}
func (x *Pep) unsubscribeFromAll(ctx context.Context, host string, subJID *jid.JID) error {
nodes, err := x.pubSubRep.FetchNodes(ctx, host)
if err != nil {
return err
}
for _, n := range nodes {
if err := x.pubSubRep.DeleteNodeSubscription(ctx, subJID.ToBareJID().String(), host, n.Name); err != nil {
return err
}
log.Infof("pep: subscription removed (host: %s, node_id: %s, jid: %s)", host, n.Name, subJID.ToBareJID().String())
}
return nil
}
func (x *Pep) deliverLastItems(ctx context.Context, jid *jid.JID) error {
nodes, err := x.pubSubRep.FetchSubscribedNodes(ctx, jid.ToBareJID().String())
if err != nil {
return err
}
for _, node := range nodes {
if node.Options.SendLastPublishedItem != pubsubmodel.OnSubAndPresence {
continue
}
aff, err := x.pubSubRep.FetchNodeAffiliation(ctx, node.Host, node.Name, jid.ToBareJID().String())
if err != nil {
return err
}
accessChecker := &accessChecker{
host: node.Host,
nodeID: node.Name,
accessModel: node.Options.AccessModel,
rosterAllowedGroups: node.Options.RosterGroupsAllowed,
affiliation: aff,
rosterRep: x.rosterRep,
}
if err := x.sendLastPublishedItem(ctx, jid, accessChecker, node.Host, node.Name, node.Options.NotificationType); err != nil {
return err
}
log.Infof("pep: delivered last item: %s (node: %s, host: %s)", jid.String(), node.Host, node.Name)
}
return nil
}
func (x *Pep) processRequest(ctx context.Context, iq *xmpp.IQ, pubSubEl xmpp.XElement) {
// Create node
if cmdEl := pubSubEl.Elements().Child("create"); cmdEl != nil && iq.IsSet() {
x.withCommandContext(ctx, commandOptions{}, cmdEl, iq, func(cmdCtx *commandContext) {
x.create(ctx, cmdCtx, pubSubEl, iq)
})
return
}
// Publish
if cmdEl := pubSubEl.Elements().Child("publish"); cmdEl != nil && iq.IsSet() {
opts := commandOptions{
allowedAffiliations: []string{pubsubmodel.Owner, pubsubmodel.Member},
includeSubscriptions: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.publish(ctx, cmdCtx, cmdEl, iq)
})
return
}
// Subscribe
if cmdEl := pubSubEl.Elements().Child("subscribe"); cmdEl != nil && iq.IsSet() {
opts := commandOptions{
includeAffiliations: true,
checkAccess: true,
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.subscribe(ctx, cmdCtx, cmdEl, iq)
})
return
}
// Unsubscribe
if cmdEl := pubSubEl.Elements().Child("unsubscribe"); cmdEl != nil && iq.IsSet() {
opts := commandOptions{
includeAffiliations: true,
includeSubscriptions: true,
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.unsubscribe(ctx, cmdCtx, cmdEl, iq)
})
return
}
// Retrieve items
if cmdEl := pubSubEl.Elements().Child("items"); cmdEl != nil && iq.IsGet() {
opts := commandOptions{
includeSubscriptions: true,
checkAccess: true,
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.retrieveItems(ctx, cmdCtx, cmdEl, iq)
})
return
}
_ = x.router.Route(ctx, iq.ServiceUnavailableError())
}
func (x *Pep) processOwnerRequest(ctx context.Context, iq *xmpp.IQ, pubSub xmpp.XElement) {
// Configure node
if cmdEl := pubSub.Elements().Child("configure"); cmdEl != nil {
if iq.IsGet() {
// send configuration form
opts := commandOptions{
allowedAffiliations: []string{pubsubmodel.Owner},
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.sendConfigurationForm(ctx, cmdCtx, iq)
})
} else if iq.IsSet() {
// update node configuration
opts := commandOptions{
allowedAffiliations: []string{pubsubmodel.Owner},
includeSubscriptions: true,
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.configure(ctx, cmdCtx, cmdEl, iq)
})
} else {
_ = x.router.Route(ctx, iq.ServiceUnavailableError())
}
return
}
// Manage affiliations
if cmdEl := pubSub.Elements().Child("affiliations"); cmdEl != nil {
if iq.IsGet() {
opts := commandOptions{
allowedAffiliations: []string{pubsubmodel.Owner},
includeAffiliations: true,
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.retrieveAffiliations(ctx, cmdCtx, iq)
})
} else if iq.IsSet() {
opts := commandOptions{
allowedAffiliations: []string{pubsubmodel.Owner},
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.updateAffiliations(ctx, cmdCtx, cmdEl, iq)
})
} else {
_ = x.router.Route(ctx, iq.ServiceUnavailableError())
}
return
}
// Manage subscriptions
if cmdEl := pubSub.Elements().Child("subscriptions"); cmdEl != nil {
if iq.IsGet() {
opts := commandOptions{
allowedAffiliations: []string{pubsubmodel.Owner},
includeSubscriptions: true,
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.retrieveSubscriptions(ctx, cmdCtx, iq)
})
} else if iq.IsSet() {
opts := commandOptions{
allowedAffiliations: []string{pubsubmodel.Owner},
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.updateSubscriptions(ctx, cmdCtx, cmdEl, iq)
})
} else {
_ = x.router.Route(ctx, iq.ServiceUnavailableError())
}
return
}
// Delete node
if cmdEl := pubSub.Elements().Child("delete"); cmdEl != nil && iq.IsSet() {
opts := commandOptions{
allowedAffiliations: []string{pubsubmodel.Owner},
includeSubscriptions: true,
failOnNotFound: true,
}
x.withCommandContext(ctx, opts, cmdEl, iq, func(cmdCtx *commandContext) {
x.delete(ctx, cmdCtx, iq)
})
return
}
_ = x.router.Route(ctx, iq.FeatureNotImplementedError())
}
func (x *Pep) create(ctx context.Context, cmdCtx *commandContext, pubSubEl xmpp.XElement, iq *xmpp.IQ) {
if cmdCtx.node != nil {
_ = x.router.Route(ctx, iq.ConflictError())
return
}
node := &pubsubmodel.Node{
Host: cmdCtx.host,
Name: cmdCtx.nodeID,
}
if configEl := pubSubEl.Elements().Child("configure"); configEl != nil {
form, err := xep0004.NewFormFromElement(configEl)
if err != nil {
_ = x.router.Route(ctx, iq.BadRequestError())
return
}
opts, err := pubsubmodel.NewOptionsFromSubmitForm(form)
if err != nil {
_ = x.router.Route(ctx, iq.BadRequestError())
return
}
node.Options = *opts
} else {
// apply default configuration
node.Options = defaultNodeOptions
}
if err := x.createNode(ctx, node); err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
log.Infof("pep: created node (host: %s, node_id: %s)", cmdCtx.host, cmdCtx.nodeID)
_ = x.router.Route(ctx, iq.ResultIQ())
}
func (x *Pep) sendConfigurationForm(ctx context.Context, cmdCtx *commandContext, iq *xmpp.IQ) {
// compose config form response
configureNode := xmpp.NewElementName("configure")
configureNode.SetAttribute("node", cmdCtx.nodeID)
rosterGroups, err := x.rosterRep.FetchRosterGroups(ctx, iq.ToJID().Node())
if err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
configureNode.AppendElement(cmdCtx.node.Options.Form(rosterGroups).Element())
pubSubNode := xmpp.NewElementNamespace("pubsub", pubSubOwnerNamespace)
pubSubNode.AppendElement(configureNode)
res := iq.ResultIQ()
res.AppendElement(pubSubNode)
log.Infof("pep: sent configuration form (host: %s, node_id: %s)", cmdCtx.host, cmdCtx.nodeID)
_ = x.router.Route(ctx, res)
}
func (x *Pep) configure(ctx context.Context, cmdCtx *commandContext, cmdElem xmpp.XElement, iq *xmpp.IQ) {
formEl := cmdElem.Elements().ChildNamespace("x", xep0004.FormNamespace)
if formEl == nil {
_ = x.router.Route(ctx, iq.NotAcceptableError())
return
}
configForm, err := xep0004.NewFormFromElement(formEl)
if err != nil {
_ = x.router.Route(ctx, iq.NotAcceptableError())
return
}
nodeOpts, err := pubsubmodel.NewOptionsFromSubmitForm(configForm)
if err != nil {
_ = x.router.Route(ctx, iq.NotAcceptableError())
return
}
cmdCtx.node.Options = *nodeOpts
// update node config
if err := x.pubSubRep.UpsertNode(ctx, cmdCtx.node); err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
// notify config update
opts := cmdCtx.node.Options
if opts.DeliverNotifications && opts.NotifyConfig {
configElem := xmpp.NewElementName("configuration")
configElem.SetAttribute("node", cmdCtx.nodeID)
if opts.DeliverPayloads {
configElem.AppendElement(opts.ResultForm().Element())
}
x.notifySubscribers(
ctx,
configElem,
cmdCtx.subscriptions,
cmdCtx.accessChecker,
cmdCtx.host,
cmdCtx.nodeID,
opts.NotificationType)
}
log.Infof("pep: node configuration updated (host: %s, node_id: %s)", cmdCtx.host, cmdCtx.nodeID)
_ = x.router.Route(ctx, iq.ResultIQ())
}
func (x *Pep) delete(ctx context.Context, cmdCtx *commandContext, iq *xmpp.IQ) {
// delete node
if err := x.pubSubRep.DeleteNode(ctx, cmdCtx.host, cmdCtx.nodeID); err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
// notify delete
opts := cmdCtx.node.Options
if opts.DeliverNotifications && opts.NotifyDelete {
deleteElem := xmpp.NewElementName("delete")
deleteElem.SetAttribute("node", cmdCtx.nodeID)
x.notifySubscribers(
ctx,
deleteElem,
cmdCtx.subscriptions,
cmdCtx.accessChecker,
cmdCtx.host,
cmdCtx.nodeID,
opts.NotificationType)
}
log.Infof("pep: deleted node (host: %s, node_id: %s)", cmdCtx.host, cmdCtx.nodeID)
x.registerDiscoItems(ctx)
_ = x.router.Route(ctx, iq.ResultIQ())
}
func (x *Pep) subscribe(ctx context.Context, cmdCtx *commandContext, cmdEl xmpp.XElement, iq *xmpp.IQ) {
// validate JID portion
subJID := cmdEl.Attributes().Get("jid")
if subJID != iq.FromJID().ToBareJID().String() {
_ = x.router.Route(ctx, invalidJIDError(iq))
return
}
// create subscription
subID := subscriptionID(subJID, cmdCtx.host, cmdCtx.nodeID)
sub := pubsubmodel.Subscription{
SubID: subID,
JID: subJID,
Subscription: pubsubmodel.Subscribed,
}
err := x.pubSubRep.UpsertNodeSubscription(ctx, &sub, cmdCtx.host, cmdCtx.nodeID)
if err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
log.Infof("pep: subscription created (host: %s, node_id: %s, jid: %s)", cmdCtx.host, cmdCtx.nodeID, subJID)
// notify subscription update
subscriptionElem := xmpp.NewElementName("subscription")
subscriptionElem.SetAttribute("node", cmdCtx.nodeID)
subscriptionElem.SetAttribute("jid", subJID)
subscriptionElem.SetAttribute("subid", subID)
subscriptionElem.SetAttribute("subscription", pubsubmodel.Subscribed)
opts := cmdCtx.node.Options
if opts.DeliverNotifications && opts.NotifySub {
x.notifyOwners(ctx, subscriptionElem, cmdCtx.affiliations, cmdCtx.host, opts.NotificationType)
}
// send last node item
switch opts.SendLastPublishedItem {
case pubsubmodel.OnSub, pubsubmodel.OnSubAndPresence:
subscriberJID, _ := jid.NewWithString(sub.JID, true)
err := x.sendLastPublishedItem(ctx, subscriberJID, cmdCtx.accessChecker, cmdCtx.host, cmdCtx.nodeID, opts.NotificationType)
if err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
}
// compose response
iqRes := iq.ResultIQ()
pubSubElem := xmpp.NewElementNamespace("pubsub", pubSubNamespace)
pubSubElem.AppendElement(subscriptionElem)
iqRes.AppendElement(pubSubElem)
_ = x.router.Route(ctx, iqRes)
}
func (x *Pep) unsubscribe(ctx context.Context, cmdCtx *commandContext, cmdEl xmpp.XElement, iq *xmpp.IQ) {
subJID := cmdEl.Attributes().Get("jid")
if subJID != iq.FromJID().ToBareJID().String() {
_ = x.router.Route(ctx, iq.ForbiddenError())
return
}
var subscription *pubsubmodel.Subscription
for _, sub := range cmdCtx.subscriptions {
if sub.JID == subJID {
subscription = &sub
break
}
}
if subscription == nil {
_ = x.router.Route(ctx, notSubscribedError(iq))
return
}
// delete subscription
if err := x.pubSubRep.DeleteNodeSubscription(ctx, subJID, cmdCtx.host, cmdCtx.nodeID); err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
log.Infof("pep: subscription removed (host: %s, node_id: %s, jid: %s)", cmdCtx.host, cmdCtx.nodeID, subJID)
// notify subscription update
subscriptionElem := xmpp.NewElementName("subscription")
subscriptionElem.SetAttribute("node", cmdCtx.nodeID)
subscriptionElem.SetAttribute("jid", subJID)
subscriptionElem.SetAttribute("subid", subscription.SubID)
subscriptionElem.SetAttribute("subscription", pubsubmodel.None)
opts := cmdCtx.node.Options
if opts.DeliverNotifications && opts.NotifySub {
x.notifyOwners(ctx, subscriptionElem, cmdCtx.affiliations, cmdCtx.host, opts.NotificationType)
}
// compose response
iqRes := iq.ResultIQ()
pubSubElem := xmpp.NewElementNamespace("pubsub", pubSubNamespace)
pubSubElem.AppendElement(subscriptionElem)
iqRes.AppendElement(pubSubElem)
_ = x.router.Route(ctx, iqRes)
}
func (x *Pep) publish(ctx context.Context, cmdCtx *commandContext, cmdEl xmpp.XElement, iq *xmpp.IQ) {
itemEl := cmdEl.Elements().Child("item")
if itemEl == nil || len(itemEl.Elements().All()) != 1 {
_ = x.router.Route(ctx, invalidPayloadError(iq))
return
}
itemID := itemEl.Attributes().Get("id")
if len(itemID) == 0 {
// generate unique item identifier
itemID = uuid.New().String()
}
// auto create node
if cmdCtx.node == nil {
if !cmdCtx.isAccountOwner {
_ = x.router.Route(ctx, iq.ForbiddenError())
return
}
cmdCtx.node = &pubsubmodel.Node{
Host: cmdCtx.host,
Name: cmdCtx.nodeID,
Options: defaultNodeOptions,
}
cmdCtx.subscriptions = []pubsubmodel.Subscription{{
JID: cmdCtx.host,
SubID: subscriptionID(cmdCtx.host, cmdCtx.host, cmdCtx.nodeID),
Subscription: pubsubmodel.Subscribed,
}}
if err := x.createNode(ctx, cmdCtx.node); err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
}
// persist node item
opts := cmdCtx.node.Options
if opts.PersistItems {
err := x.pubSubRep.UpsertNodeItem(ctx, &pubsubmodel.Item{
ID: itemID,
Publisher: iq.FromJID().ToBareJID().String(),
Payload: itemEl.Elements().All()[0],
}, cmdCtx.host, cmdCtx.nodeID, int(opts.MaxItems))
if err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
}
log.Infof("pep: published item (host: %s, node_id: %s, item_id: %s)", cmdCtx.host, cmdCtx.nodeID, itemID)
// notify published item
itemsElem := xmpp.NewElementName("items")
itemsElem.SetAttribute("node", cmdCtx.nodeID)
itemElem := xmpp.NewElementName("item")
itemElem.SetAttribute("id", itemID)
if opts.DeliverPayloads || !opts.PersistItems {
itemElem.AppendElement(itemEl.Elements().All()[0])
}
itemsElem.AppendElement(itemElem)
x.notifySubscribers(
ctx,
itemsElem,
cmdCtx.subscriptions,
cmdCtx.accessChecker,
cmdCtx.host,
cmdCtx.nodeID,
cmdCtx.node.Options.NotificationType)
// compose response
publishElem := xmpp.NewElementName("publish")
publishElem.SetAttribute("node", cmdCtx.nodeID)
resItemElem := xmpp.NewElementName("item")
resItemElem.SetAttribute("id", itemID)
publishElem.AppendElement(resItemElem)
iqRes := iq.ResultIQ()
pubSubElem := xmpp.NewElementNamespace("pubsub", pubSubNamespace)
pubSubElem.AppendElement(publishElem)
iqRes.AppendElement(pubSubElem)
_ = x.router.Route(ctx, iqRes)
}
func (x *Pep) retrieveItems(ctx context.Context, cmdCtx *commandContext, cmdEl xmpp.XElement, iq *xmpp.IQ) {
var itemIDs []string
itemElems := cmdEl.Elements().Children("item")
if len(itemElems) > 0 {
for _, itemEl := range itemElems {
itemID := itemEl.Attributes().Get("id")
if len(itemID) == 0 {
continue
}
itemIDs = append(itemIDs, itemID)
}
}
// retrieve node items
var items []pubsubmodel.Item
var err error
if len(itemIDs) > 0 {
items, err = x.pubSubRep.FetchNodeItemsWithIDs(ctx, cmdCtx.host, cmdCtx.nodeID, itemIDs)
} else {
items, err = x.pubSubRep.FetchNodeItems(ctx, cmdCtx.host, cmdCtx.nodeID)
}
if err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
log.Infof("pep: retrieved items (host: %s, node_id: %s)", cmdCtx.host, cmdCtx.nodeID)
// compose response
iqRes := iq.ResultIQ()
pubSubElem := xmpp.NewElementNamespace("pubsub", pubSubNamespace)
itemsElem := xmpp.NewElementName("items")
itemsElem.SetAttribute("node", cmdCtx.nodeID)
for _, itm := range items {
itemElem := xmpp.NewElementName("item")
itemElem.SetAttribute("id", itm.ID)
itemElem.AppendElement(itm.Payload)
itemsElem.AppendElement(itemElem)
}
pubSubElem.AppendElement(itemsElem)
iqRes.AppendElement(pubSubElem)
_ = x.router.Route(ctx, iqRes)
}
func (x *Pep) retrieveAffiliations(ctx context.Context, cmdCtx *commandContext, iq *xmpp.IQ) {
affiliationsElem := xmpp.NewElementName("affiliations")
affiliationsElem.SetAttribute("node", cmdCtx.nodeID)
for _, aff := range cmdCtx.affiliations {
affElem := xmpp.NewElementName("affiliation")
affElem.SetAttribute("jid", aff.JID)
affElem.SetAttribute("affiliation", aff.Affiliation)
affiliationsElem.AppendElement(affElem)
}
log.Infof("pep: retrieved affiliations (host: %s, node_id: %s)", cmdCtx.host, cmdCtx.nodeID)
// compose response
iqRes := iq.ResultIQ()
pubSubElem := xmpp.NewElementNamespace("pubsub", pubSubOwnerNamespace)
pubSubElem.AppendElement(affiliationsElem)
iqRes.AppendElement(pubSubElem)
_ = x.router.Route(ctx, iqRes)
}
func (x *Pep) updateAffiliations(ctx context.Context, cmdCtx *commandContext, cmdElem xmpp.XElement, iq *xmpp.IQ) {
// update affiliations
for _, affElem := range cmdElem.Elements().Children("affiliation") {
var aff pubsubmodel.Affiliation
aff.JID = affElem.Attributes().Get("jid")
aff.Affiliation = affElem.Attributes().Get("affiliation")
if aff.JID == cmdCtx.host {
// ignore node owner affiliation update
continue
}
var err error
switch aff.Affiliation {
case pubsubmodel.Owner, pubsubmodel.Member, pubsubmodel.Publisher, pubsubmodel.Outcast:
err = x.pubSubRep.UpsertNodeAffiliation(ctx, &aff, cmdCtx.host, cmdCtx.nodeID)
case pubsubmodel.None:
err = x.pubSubRep.DeleteNodeAffiliation(ctx, aff.JID, cmdCtx.host, cmdCtx.nodeID)
default:
_ = x.router.Route(ctx, iq.BadRequestError())
return
}
if err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
}
log.Infof("pep: modified affiliations (host: %s, node_id: %s)", cmdCtx.host, cmdCtx.nodeID)
_ = x.router.Route(ctx, iq.ResultIQ())
}
func (x *Pep) retrieveSubscriptions(ctx context.Context, cmdCtx *commandContext, iq *xmpp.IQ) {
subscriptionsElem := xmpp.NewElementName("subscriptions")
subscriptionsElem.SetAttribute("node", cmdCtx.nodeID)
for _, sub := range cmdCtx.subscriptions {
subElem := xmpp.NewElementName("subscription")
subElem.SetAttribute("subid", sub.SubID)
subElem.SetAttribute("jid", sub.JID)
subElem.SetAttribute("subscription", sub.Subscription)
subscriptionsElem.AppendElement(subElem)
}
log.Infof("pep: retrieved subscriptions (host: %s, node_id: %s)", cmdCtx.host, cmdCtx.nodeID)
// compose response
iqRes := iq.ResultIQ()
pubSubElem := xmpp.NewElementNamespace("pubsub", pubSubOwnerNamespace)
pubSubElem.AppendElement(subscriptionsElem)
iqRes.AppendElement(pubSubElem)
_ = x.router.Route(ctx, iqRes)
}
func (x *Pep) updateSubscriptions(ctx context.Context, cmdCtx *commandContext, cmdElem xmpp.XElement, iq *xmpp.IQ) {
// update subscriptions
for _, subElem := range cmdElem.Elements().Children("subscription") {
var sub pubsubmodel.Subscription
sub.SubID = subElem.Attributes().Get("subid")
sub.JID = subElem.Attributes().Get("jid")
sub.Subscription = subElem.Attributes().Get("subscription")
if sub.JID == cmdCtx.host {
// ignore node owner subscription update
continue
}
var err error
switch sub.Subscription {
case pubsubmodel.Subscribed:
err = x.pubSubRep.UpsertNodeSubscription(ctx, &sub, cmdCtx.host, cmdCtx.nodeID)
case pubsubmodel.None:
err = x.pubSubRep.DeleteNodeSubscription(ctx, sub.JID, cmdCtx.host, cmdCtx.nodeID)
default:
_ = x.router.Route(ctx, iq.BadRequestError())
return
}
if err != nil {
log.Error(err)
_ = x.router.Route(ctx, iq.InternalServerError())
return
}
}
log.Infof("pep: modified subscriptions (host: %s, node_id: %s)", cmdCtx.host, cmdCtx.nodeID)
_ = x.router.Route(ctx, iq.ResultIQ())
}
func (x *Pep) notifyOwners(ctx context.Context, notificationElem xmpp.XElement, affiliations []pubsubmodel.Affiliation, host, notificationType string) {
hostJID, _ := jid.NewWithString(host, true)
for _, affiliation := range affiliations {
if affiliation.Affiliation != pubsubmodel.Owner {
continue
}
toJID, _ := jid.NewWithString(affiliation.JID, true)
eventMsg := eventMessage(notificationElem, hostJID, toJID, notificationType)
_ = x.router.Route(ctx, eventMsg)
}
}
func (x *Pep) notifySubscribers(
ctx context.Context,
notificationElem xmpp.XElement,
subscribers []pubsubmodel.Subscription,
accessChecker *accessChecker,
host string,
nodeID string,
notificationType string,
) {
var toJIDs []jid.JID
for _, subscriber := range subscribers {
if subscriber.Subscription != pubsubmodel.Subscribed {
continue
}
subscriberJID, _ := jid.NewWithString(subscriber.JID, true)
toJIDs = append(toJIDs, *subscriberJID)
}
x.notify(ctx, notificationElem, toJIDs, accessChecker, host, nodeID, notificationType)
}
func (x *Pep) notify(
ctx context.Context,
notificationElem xmpp.XElement,
toJIDs []jid.JID,
accessChecker *accessChecker,
host string,
nodeID string,
notificationType string,
) {
hostJID, _ := jid.NewWithString(host, true)
for _, toJID := range toJIDs {
if toJID.ToBareJID().String() != host {
// check JID access before notifying
err := accessChecker.checkAccess(ctx, toJID.ToBareJID().String())
switch err {
case nil:
break
case errPresenceSubscriptionRequired, errNotInRosterGroup, errNotOnWhiteList:
continue
default:
log.Error(err)
continue
}
}
if ph := x.entityCaps; ph != nil {
onlinePresences, err := ph.PresencesMatchingJID(ctx, &toJID)
if err != nil {
log.Error(err)
}
for _, onlinePresence := range onlinePresences {
caps := onlinePresence.Caps
if caps == nil {
goto broadcastEventMsg // broadcast when caps are pending to be fetched
}
if !caps.HasFeature(nodeID + "+notify") {
continue
}
// notify to full jid
presence := onlinePresence.Presence
eventMsg := eventMessage(notificationElem, hostJID, presence.FromJID(), notificationType)