File: pubsub.py

package info (click to toggle)
python-tx-xmpp 0.10.1.post1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,468 kB
  • sloc: python: 12,915; makefile: 3
file content (1690 lines) | stat: -rw-r--r-- 58,654 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
# -*- coding: utf-8 -*-
# -*- test-case-name: tx_xmpp.test.test.test_pubsub -*-
#
# Copyright (c) Ralph Meijer, 2007-2021
# Copyright (c) Adrien Cossa, 2016
# Copyright (c) Jรฉrรดme Poisson, 2017-2026
# See LICENSE for details.

"""
XMPP publish-subscribe protocol.

This protocol is specified in
U{XEP-0060<http://xmpp.org/extensions/xep-0060.html>}.
"""

from __future__ import division, absolute_import
from typing import Optional

from zope.interface import implementer

from twisted.internet import defer
from twisted.python import log
from twisted.words.protocols.jabber import jid, error
from twisted.words.xish import domish

from . import disco, data_form, generic, shim
from .compat import IQ
from .subprotocols import IQHandlerMixin, XMPPHandler
from .itx_xmpp import IPubSubClient, IPubSubService, IPubSubResource

# Iq get and set XPath queries
IQ_GET = '/iq[@type="get"]'
IQ_SET = '/iq[@type="set"]'

# Publish-subscribe namespaces
NS_PUBSUB = "http://jabber.org/protocol/pubsub"
NS_PUBSUB_EVENT = NS_PUBSUB + "#event"
NS_PUBSUB_ERRORS = NS_PUBSUB + "#errors"
NS_PUBSUB_OWNER = NS_PUBSUB + "#owner"
NS_PUBSUB_NODE_CONFIG = NS_PUBSUB + "#node_config"
NS_PUBSUB_META_DATA = NS_PUBSUB + "#meta-data"
NS_PUBSUB_SUBSCRIBE_OPTIONS = NS_PUBSUB + "#subscribe_options"
NS_PUBSUB_PUBLISH_OPTIONS = NS_PUBSUB + "#publish-options"

NS_ORDER_BY = "urn:xmpp:order-by:0"

# XPath to match pubsub requests
PUBSUB_REQUEST = (
    '/iq[@type="get" or @type="set"]/'
    + 'pubsub[@xmlns="'
    + NS_PUBSUB
    + '" or '
    + '@xmlns="'
    + NS_PUBSUB_OWNER
    + '"]'
)

BOOL_TRUE = ("1", "true")
BOOL_FALSE = ("0", "false")


class SubscriptionPending(Exception):
    """
    Raised when the requested subscription is pending acceptance.
    """


class SubscriptionUnconfigured(Exception):
    """
    Raised when the requested subscription needs to be configured before
    becoming active.
    """


class PubSubError(error.StanzaError):
    """
    Exception with publish-subscribe specific condition.
    """

    def __init__(self, condition, pubsubCondition, feature=None, text=None):
        appCondition = domish.Element((NS_PUBSUB_ERRORS, pubsubCondition))
        if feature:
            appCondition["feature"] = feature
        error.StanzaError.__init__(self, condition, text=text, appCondition=appCondition)


class BadRequest(error.StanzaError):
    """
    Bad request stanza error.
    """

    def __init__(self, pubsubCondition=None, text=None):
        if pubsubCondition:
            appCondition = domish.Element((NS_PUBSUB_ERRORS, pubsubCondition))
        else:
            appCondition = None
        error.StanzaError.__init__(
            self, "bad-request", text=text, appCondition=appCondition
        )


class Unsupported(PubSubError):
    def __init__(self, feature, text=None):
        self.feature = feature
        PubSubError.__init__(
            self, "feature-not-implemented", "unsupported", feature, text
        )

    def __str__(self):
        message = PubSubError.__str__(self)
        message += ", feature %r" % self.feature
        return message


class Subscription(object):
    """
    A subscription to a node.

    @ivar nodeIdentifier: The identifier of the node subscribed to.  The root
        node is denoted by L{None}.
    @type nodeIdentifier: L{str}

    @ivar subscriber: The subscribing entity.
    @type subscriber: L{jid.JID}

    @ivar state: The subscription state. One of C{'subscribed'}, C{'pending'},
                 C{'unconfigured'}.
    @type state: L{str}

    @ivar options: Optional list of subscription options.
    @type options: L{dict}

    @ivar subscriptionIdentifier: Optional subscription identifier.
    @type subscriptionIdentifier: L{str}
    """

    def __init__(
        self, nodeIdentifier, subscriber, state, options=None, subscriptionIdentifier=None
    ):
        self.nodeIdentifier = nodeIdentifier
        self.subscriber = subscriber
        self.state = state
        self.options = options or {}
        self.subscriptionIdentifier = subscriptionIdentifier

    @staticmethod
    def fromElement(element):
        return Subscription(
            element.getAttribute("node"),
            jid.JID(element.getAttribute("jid")),
            element.getAttribute("subscription"),
            subscriptionIdentifier=element.getAttribute("subid"),
        )

    def toElement(self, defaultUri=None):
        """
        Return the DOM representation of this subscription.

        @rtype: L{domish.Element}
        """
        element = domish.Element((defaultUri, "subscription"))
        if self.nodeIdentifier:
            element["node"] = self.nodeIdentifier
        element["jid"] = str(self.subscriber)
        element["subscription"] = self.state
        if self.subscriptionIdentifier:
            element["subid"] = self.subscriptionIdentifier
        return element


class Item(domish.Element):
    """
    Publish subscribe item.

    This behaves like an object providing L{domish.IElement}.

    Item payload can be added using C{addChild} or C{addRawXml}, or using the
    C{payload} keyword argument to C{__init__}.
    """

    def __init__(self, id=None, payload=None):
        """
        @param id: optional item identifier
        @type id: L{str}
        @param payload: optional item payload. Either as a domish element, or
                        as serialized XML.
        @type payload: object providing L{domish.IElement} or L{str}.
        """

        domish.Element.__init__(self, (None, "item"))
        if id is not None:
            self["id"] = id
        if payload is not None:
            if isinstance(payload, str):
                self.addRawXml(payload)
            else:
                self.addChild(payload)


class PubSubRequest(generic.Stanza):
    """
    A publish-subscribe request.

    The set of instance variables used depends on the type of request. If
    a variable is not applicable or not passed in the request, its value is
    L{None}.

    @ivar verb: The type of publish-subscribe request. See C{_requestVerbMap}.
    @type verb: L{str}.

    @ivar affiliations: Affiliations to be modified.
    @type affiliations: L{set}

    @ivar items: The items to be published, as L{domish.Element}s.
    @type items: L{list}

    @ivar itemIdentifiers: Identifiers of the items to be retrieved or
                           retracted.
    @type itemIdentifiers: L{set}

    @ivar maxItems: Maximum number of items to retrieve.
    @type maxItems: L{int}.

    @ivar nodeIdentifier: Identifier of the node the request is about.
    @type nodeIdentifier: L{str}

    @ivar nodeType: The type of node that should be created, or for which the
                    configuration is retrieved. C{'leaf'} or C{'collection'}.
    @type nodeType: L{str}

    @ivar options: Configurations options for nodes, subscriptions and publish
                   requests.
    @type options: L{data_form.Form}

    @ivar subscriber: The subscribing entity.
    @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}

    @ivar subscriptionIdentifier: Identifier for a specific subscription.
    @type subscriptionIdentifier: L{str}

    @ivar subscriptions: Subscriptions to be modified, as a set of
        L{Subscription}.
    @type subscriptions: L{set}

    @ivar affiliations: Affiliations to be modified, as a dictionary of entity
        (L{JID<twisted.words.protocols.jabber.jid.JID>} to affiliation
        (L{str}).
    @type affiliations: L{dict}
    """

    verb = None

    affiliations = None
    items = None
    itemIdentifiers = None
    maxItems = None
    nodeIdentifier = None
    nodeType = None
    options = None
    subscriber = None
    subscriptionIdentifier = None
    subscriptions = None
    affiliations = None
    notify = None
    orderBy = None

    # Map request iq type and subelement name to request verb
    _requestVerbMap = {
        ("set", NS_PUBSUB, "publish"): "publish",
        ("set", NS_PUBSUB, "subscribe"): "subscribe",
        ("set", NS_PUBSUB, "unsubscribe"): "unsubscribe",
        ("get", NS_PUBSUB, "options"): "optionsGet",
        ("set", NS_PUBSUB, "options"): "optionsSet",
        ("get", NS_PUBSUB, "subscriptions"): "subscriptions",
        ("get", NS_PUBSUB, "affiliations"): "affiliations",
        ("set", NS_PUBSUB, "create"): "create",
        ("get", NS_PUBSUB_OWNER, "default"): "default",
        ("get", NS_PUBSUB_OWNER, "configure"): "configureGet",
        ("set", NS_PUBSUB_OWNER, "configure"): "configureSet",
        ("get", NS_PUBSUB, "items"): "items",
        ("set", NS_PUBSUB, "retract"): "retract",
        ("set", NS_PUBSUB_OWNER, "purge"): "purge",
        ("set", NS_PUBSUB_OWNER, "delete"): "delete",
        ("get", NS_PUBSUB_OWNER, "affiliations"): "affiliationsGet",
        ("set", NS_PUBSUB_OWNER, "affiliations"): "affiliationsSet",
        ("get", NS_PUBSUB_OWNER, "subscriptions"): "subscriptionsGet",
        ("set", NS_PUBSUB_OWNER, "subscriptions"): "subscriptionsSet",
    }

    # Map request verb to request iq type and subelement name
    _verbRequestMap = dict(((v, k) for k, v in _requestVerbMap.items()))

    # Map request verb to parameter handler names
    _parameters = {
        "publish": ["node", "items", "publishOptionsOrNone"],
        "subscribe": ["nodeOrEmpty", "jid", "optionsWithSubscribe"],
        "unsubscribe": ["nodeOrEmpty", "jid", "subidOrNone"],
        "optionsGet": ["nodeOrEmpty", "jid", "subidOrNone"],
        "optionsSet": ["nodeOrEmpty", "jid", "options", "subidOrNone"],
        "subscriptions": ["nodeOrNone"],
        "affiliations": ["nodeOrNone"],
        "create": ["nodeOrNone", "configureOrNone"],
        "default": ["default"],
        "configureGet": ["nodeOrEmpty"],
        "configureSet": ["nodeOrEmpty", "configureOrNone"],
        "items": ["node", "maxItems", "itemIdentifiers", "subidOrNone", "orderBy"],
        "retract": ["node", "notify", "itemIdentifiers"],
        "purge": ["node"],
        "delete": ["node"],
        "affiliationsGet": ["nodeOrNone"],
        "affiliationsSet": ["node", "affiliations"],
        "subscriptionsGet": ["nodeOrNone"],
        "subscriptionsSet": ["node", "subscriptions"],
    }

    def __init__(self, verb=None):
        self.verb = verb

    def _parse_node(self, verbElement):
        """
        Parse the required node identifier out of the verbElement.
        """
        try:
            self.nodeIdentifier = verbElement["node"]
        except KeyError:
            raise BadRequest("nodeid-required")

    def _render_node(self, verbElement):
        """
        Render the required node identifier on the verbElement.
        """
        if not self.nodeIdentifier:
            raise Exception("Node identifier is required")

        verbElement["node"] = self.nodeIdentifier

    def _parse_nodeOrEmpty(self, verbElement):
        """
        Parse the node identifier out of the verbElement. May be empty.
        """
        self.nodeIdentifier = verbElement.getAttribute("node", "")

    def _render_nodeOrEmpty(self, verbElement):
        """
        Render the node identifier on the verbElement. May be empty.
        """
        if self.nodeIdentifier:
            verbElement["node"] = self.nodeIdentifier

    def _parse_nodeOrNone(self, verbElement):
        """
        Parse the optional node identifier out of the verbElement.
        """
        self.nodeIdentifier = verbElement.getAttribute("node")

    def _render_nodeOrNone(self, verbElement):
        """
        Render the optional node identifier on the verbElement.
        """
        if self.nodeIdentifier:
            verbElement["node"] = self.nodeIdentifier

    def _parse_items(self, verbElement):
        """
        Parse items out of the verbElement for publish requests.
        """
        self.items = []
        for element in verbElement.elements():
            if element.uri == NS_PUBSUB and element.name == "item":
                self.items.append(element)

    def _render_items(self, verbElement):
        """
        Render items into the verbElement for publish requests.
        """
        if self.items:
            for item in self.items:
                item.uri = NS_PUBSUB
                verbElement.addChild(item)

    def _parse_publishOptionsOrNone(self, verbElement):
        """
        Parse optional publish-options form in publish request.
        """
        for element in verbElement.parent.elements():
            form = data_form.findForm(element, NS_PUBSUB_PUBLISH_OPTIONS)
            if form is not None:
                if form.formType != "submit":
                    raise BadRequest(text="Unexpected form type '%s'" % form.formType)
            else:
                form = data_form.Form("submit", formNamespace=NS_PUBSUB_PUBLISH_OPTIONS)

            self.options = form

    def _render_publishOptionsOrNone(self, verbElement):
        if self.options is not None:
            if self.options.formType != "submit":
                log.err(
                    "Invalid type for publish-options form ({formType}): {xml}".format(
                        formType=self.options.formType, xml=verbElement.toXml()
                    )
                )
                return
            publishOptions = verbElement.parent.addElement("publish-options")
            publishOptions.addChild(self.options.toElement())

    def _parse_jid(self, verbElement):
        """
        Parse subscriber out of the verbElement for un-/subscribe requests.
        """
        try:
            self.subscriber = jid.internJID(verbElement["jid"])
        except KeyError:
            raise BadRequest("jid-required")

    def _render_jid(self, verbElement):
        """
        Render subscriber into the verbElement for un-/subscribe requests.
        """
        verbElement["jid"] = self.subscriber.full()

    def _parse_default(self, verbElement):
        """
        Parse node type out of a request for the default node configuration.
        """
        form = data_form.findForm(verbElement, NS_PUBSUB_NODE_CONFIG)
        if form is not None and form.formType == "submit":
            values = form.getValues()
            self.nodeType = values.get("pubsub#node_type", "leaf")
        else:
            self.nodeType = "leaf"

    def _parse_configure(self, verbElement):
        """
        Parse options out of a request for setting the node configuration.
        """
        form = data_form.findForm(verbElement, NS_PUBSUB_NODE_CONFIG)
        if form is not None:
            if form.formType in ("submit", "cancel"):
                self.options = form
            else:
                raise BadRequest(text="Unexpected form type '%s'" % form.formType)
        else:
            raise BadRequest(text="Missing configuration form")

    def _parse_configureOrNone(self, verbElement):
        """
        Parse optional node configuration form in create request.
        """
        for element in verbElement.parent.elements():
            if (
                element.uri in (NS_PUBSUB, NS_PUBSUB_OWNER)
                and element.name == "configure"
            ):
                form = data_form.findForm(element, NS_PUBSUB_NODE_CONFIG)
                if form is not None:
                    if form.formType in ("submit", "cancel"):
                        self.options = form
                    else:
                        raise BadRequest(text="Unexpected form type '%s'" % form.formType)
                else:
                    if self.verb == "create":
                        # Empty <configure/> in create request means use default config
                        self.options = data_form.Form(
                            "submit", formNamespace=NS_PUBSUB_NODE_CONFIG
                        )
                    else:
                        # For configureSet, a form is required
                        raise BadRequest(text="data form is required")

    def _render_configureOrNone(self, verbElement):
        """
        Render optional node configuration form in create request.
        """
        if self.options is not None:
            if verbElement.name == "configure":
                configure = verbElement
            else:
                configure = verbElement.parent.addElement("configure")
            configure.addChild(self.options.toElement())

    def _parse_itemIdentifiers(self, verbElement):
        """
        Parse item identifiers out of items and retract requests.
        """
        self.itemIdentifiers = []
        for element in verbElement.elements():
            if element.uri == NS_PUBSUB and element.name == "item":
                try:
                    self.itemIdentifiers.append(element["id"])
                except KeyError:
                    raise BadRequest()

    def _render_itemIdentifiers(self, verbElement):
        """
        Render item identifiers into items and retract requests.
        """
        if self.itemIdentifiers:
            for itemIdentifier in self.itemIdentifiers:
                item = verbElement.addElement("item")
                item["id"] = itemIdentifier

    def _parse_maxItems(self, verbElement):
        """
        Parse maximum items out of an items request.
        """
        value = verbElement.getAttribute("max_items")

        if value:
            try:
                self.maxItems = int(value)
            except ValueError:
                raise BadRequest(
                    text="Field max_items requires a positive " + "integer value"
                )

    def _render_maxItems(self, verbElement):
        """
        Render maximum items into an items request.
        """
        if self.maxItems:
            verbElement["max_items"] = str(self.maxItems)

    def _parse_subidOrNone(self, verbElement):
        """
        Parse subscription identifier out of a request.
        """
        self.subscriptionIdentifier = verbElement.getAttribute("subid")

    def _render_subidOrNone(self, verbElement):
        """
        Render subscription identifier into a request.
        """
        if self.subscriptionIdentifier:
            verbElement["subid"] = self.subscriptionIdentifier

    def _parse_options(self, verbElement):
        """
        Parse options form out of a subscription options request.
        """
        form = data_form.findForm(verbElement, NS_PUBSUB_SUBSCRIBE_OPTIONS)
        if form is not None:
            if form.formType in ("submit", "cancel"):
                self.options = form
            else:
                raise BadRequest(text="Unexpected form type '%s'" % form.formType)
        else:
            raise BadRequest(text="Missing options form")

    def _render_options(self, verbElement):
        verbElement.addChild(self.options.toElement())

    def _parse_optionsWithSubscribe(self, verbElement):
        for element in verbElement.parent.elements():
            if element.name == "options" and element.uri == NS_PUBSUB:
                form = data_form.findForm(element, NS_PUBSUB_SUBSCRIBE_OPTIONS)
                if form is not None:
                    if form.formType != "submit":
                        raise BadRequest(text="Unexpected form type '%s'" % form.formType)
                else:
                    form = data_form.Form(
                        "submit", formNamespace=NS_PUBSUB_SUBSCRIBE_OPTIONS
                    )
                self.options = form

    def _render_optionsWithSubscribe(self, verbElement):
        if self.options is not None:
            optionsElement = verbElement.parent.addElement("options")
            self._render_options(optionsElement)

    def _parse_affiliations(self, verbElement):
        self.affiliations = {}
        for element in verbElement.elements():
            if element.uri == NS_PUBSUB_OWNER and element.name == "affiliation":
                try:
                    entity = jid.internJID(element["jid"]).userhostJID()
                except KeyError:
                    raise BadRequest(text="Missing jid attribute")

                if entity in self.affiliations:
                    raise BadRequest(text="Multiple affiliations for an entity")

                try:
                    affiliation = element["affiliation"]
                except KeyError:
                    raise BadRequest(text="Missing affiliation attribute")

                self.affiliations[entity] = affiliation

    def _render_affiliations(self, verbElement):
        for entity, affiliation in self.affiliations.items():
            affiliationElement = verbElement.addElement((NS_PUBSUB_OWNER, "affiliation"))
            affiliationElement["jid"] = entity.full()
            affiliationElement["affiliation"] = affiliation

    def _parse_subscriptions(self, verbElement):
        self.subscriptions = set()
        seen_entities = set()
        for element in verbElement.elements():
            if element.uri == NS_PUBSUB_OWNER and element.name == "subscription":
                try:
                    subscriber = jid.internJID(element["jid"]).userhostJID()
                except KeyError:
                    raise BadRequest(text="Missing jid attribute")

                if subscriber in seen_entities:
                    raise BadRequest(text="Multiple subscriptions for an subscriber")
                seen_entities.add(subscriber)

                try:
                    state = element["subscription"]
                except KeyError:
                    # ยง8.8.2.1 says that value MUST NOT be changed
                    # if subscription is missing
                    continue

                self.subscriptions.add(
                    Subscription(self.nodeIdentifier, subscriber, state)
                )

    def _render_subscriptions(self, verbElement):
        for subscription in self.subscriptions:
            subscriptionElement = verbElement.addElement(
                (NS_PUBSUB_OWNER, "subscription")
            )
            subscriptionElement["jid"] = subscription.subscriber.full()
            subscriptionElement["subscription"] = subscription.state

    def _parse_notify(self, verbElement):
        value = verbElement.getAttribute("notify")

        if value:
            if value in BOOL_TRUE:
                self.notify = True
            elif value in BOOL_FALSE:
                self.notify = False
            else:
                raise BadRequest(text="Field notify must be a boolean value")

    def _render_notify(self, verbElement):
        if self.notify is not None:
            verbElement["notify"] = "true" if self.notify else "false"

    def _parse_orderBy(self, verbElement):
        pubsub_elt = verbElement.parent
        self.orderBy = []
        for element in pubsub_elt.elements(NS_ORDER_BY, "order"):
            self.orderBy.append(element["by"])

    def _render_orderBy(self, verbElement):
        if self.orderBy is None:
            return
        pubsub_elt = verbElement.parent
        for by_attr in self.orderBy:
            order_elt = pubsub_elt.addElement((NS_ORDER_BY, "order"))
            order_elt["by"] = by_attr

    def parseElement(self, element):
        """
        Parse the publish-subscribe verb and parameters out of a request.
        """
        generic.Stanza.parseElement(self, element)

        verbs = []
        verbElements = []
        for child in element.pubsub.elements():
            key = (self.stanzaType, child.uri, child.name)
            try:
                verb = self._requestVerbMap[key]
            except KeyError:
                continue

            verbs.append(verb)
            verbElements.append(child)

        if not verbs:
            raise NotImplementedError()

        if len(verbs) > 1:
            if "optionsSet" in verbs and "subscribe" in verbs:
                self.verb = "subscribe"
                verbElement = verbElements[verbs.index("subscribe")]
            else:
                raise NotImplementedError()
        else:
            self.verb = verbs[0]
            verbElement = verbElements[0]

        for parameter in self._parameters[self.verb]:
            getattr(self, "_parse_%s" % parameter)(verbElement)

    def send(self, xs):
        """
        Send this request to its recipient.

        This renders all of the relevant parameters for this specific
        requests into an L{IQ}, and invoke its C{send} method.
        This returns a deferred that fires upon reception of a response. See
        L{IQ} for details.

        @param xs: The XML stream to send the request on.
        @type xs: L{twisted.words.protocols.jabber.xmlstream.XmlStream}
        @rtype: L{defer.Deferred}.
        """

        try:
            self.stanzaType, childURI, childName = self._verbRequestMap[self.verb]
        except KeyError:
            raise NotImplementedError()

        iq = IQ(xs, self.stanzaType)
        iq.addElement((childURI, "pubsub"))
        verbElement = iq.pubsub.addElement(childName)

        if self.sender:
            iq["from"] = self.sender.full()
        if self.recipient:
            iq["to"] = self.recipient.full()

        for parameter in self._parameters[self.verb]:
            getattr(self, "_render_%s" % parameter)(verbElement)

        return iq.send()


class PubSubEvent(object):
    """
    A publish subscribe event.

    @param sender: The entity from which the notification was received.
    @type sender: L{jid.JID}
    @param recipient: The entity to which the notification was sent.
    @type recipient: L{tx_xmpp.pubsub.ItemsEvent}
    @param nodeIdentifier: Identifier of the node the event pertains to.
    @type nodeIdentifier: L{str}
    @param headers: SHIM headers, see L{tx_xmpp.shim.extractHeaders}.
    @type headers: L{dict}
    """

    def __init__(self, sender, recipient, nodeIdentifier, headers):
        self.sender = sender
        self.recipient = recipient
        self.nodeIdentifier = nodeIdentifier
        self.headers = headers


class ItemsEvent(PubSubEvent):
    """
    A publish-subscribe event that signifies new, updated and retracted items.

    @param items: List of received items as domish elements.
    @type items: L{list} of L{domish.Element}
    """

    def __init__(self, sender, recipient, nodeIdentifier, items, headers):
        PubSubEvent.__init__(self, sender, recipient, nodeIdentifier, headers)
        self.items = items


class DeleteEvent(PubSubEvent):
    """
    A publish-subscribe event that signifies the deletion of a node.
    """

    redirectURI = None


class PurgeEvent(PubSubEvent):
    """
    A publish-subscribe event that signifies the purging of a node.
    """


@implementer(IPubSubClient)
class PubSubClient(XMPPHandler):
    """
    Publish subscribe client protocol.
    """

    _request_class = PubSubRequest

    def connectionInitialized(self):
        self.xmlstream.addObserver(
            '/message/event[@xmlns="%s"]' % NS_PUBSUB_EVENT, self._onEvent
        )

    def _onEvent(self, message):
        if message.getAttribute("type") == "error":
            return

        try:
            sender = jid.JID(message["from"])
            recipient = jid.JID(message["to"])
        except KeyError:
            return

        actionElement = None
        for element in message.event.elements():
            if element.uri == NS_PUBSUB_EVENT:
                actionElement = element

        if not actionElement:
            return

        eventHandler = getattr(self, "_onEvent_%s" % actionElement.name, None)

        if eventHandler:
            headers = shim.extractHeaders(message)
            eventHandler(sender, recipient, actionElement, headers)
            message.handled = True

    def _onEvent_items(self, sender, recipient, action, headers):
        nodeIdentifier = action["node"]

        items = [
            element
            for element in action.elements()
            if element.name in ("item", "retract")
        ]

        event = ItemsEvent(sender, recipient, nodeIdentifier, items, headers)
        self.itemsReceived(event)

    def _onEvent_delete(self, sender, recipient, action, headers):
        nodeIdentifier = action["node"]
        event = DeleteEvent(sender, recipient, nodeIdentifier, headers)
        if action.redirect:
            event.redirectURI = action.redirect.getAttribute("uri")
        self.deleteReceived(event)

    def _onEvent_purge(self, sender, recipient, action, headers):
        nodeIdentifier = action["node"]
        event = PurgeEvent(sender, recipient, nodeIdentifier, headers)
        self.purgeReceived(event)

    def itemsReceived(self, event):
        pass

    def deleteReceived(self, event):
        pass

    def purgeReceived(self, event):
        pass

    def createNode(self, service, nodeIdentifier=None, options=None, sender=None):
        """
        Create a publish subscribe node.

        @param service: The publish subscribe service to create the node at.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: Optional suggestion for the id of the node.
        @type nodeIdentifier: L{str}
        @param options: Optional node configuration options.
        @type options: L{dict}
        """
        request = self._request_class("create")
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.sender = sender

        if options:
            form = data_form.Form(formType="submit", formNamespace=NS_PUBSUB_NODE_CONFIG)
            form.makeFields(options)
            request.options = form

        def cb(iq):
            try:
                new_node = iq.pubsub.create["node"]
            except AttributeError:
                # the suggested node identifier was accepted
                new_node = nodeIdentifier
            return new_node

        d = request.send(self.xmlstream)
        d.addCallback(cb)
        return d

    def deleteNode(self, service, nodeIdentifier, sender=None):
        """
        Delete a publish subscribe node.

        @param service: The publish subscribe service to delete the node from.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{str}
        """
        request = self._request_class("delete")
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.sender = sender
        return request.send(self.xmlstream)

    def subscribe(self, service, nodeIdentifier, subscriber, options=None, sender=None):
        """
        Subscribe to a publish subscribe node.

        @param service: The publish subscribe service that keeps the node.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{str}

        @param subscriber: The entity to subscribe to the node. This entity
            will get notifications of new published items.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param options: Subscription options.
        @type options: L{dict}

        @return: Deferred that fires with L{Subscription} or errbacks with
            L{SubscriptionPending} or L{SubscriptionUnconfigured}.
        @rtype: L{defer.Deferred}
        """
        request = self._request_class("subscribe")
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.subscriber = subscriber
        request.sender = sender

        if options:
            form = data_form.Form(
                formType="submit", formNamespace=NS_PUBSUB_SUBSCRIBE_OPTIONS
            )
            form.makeFields(options)
            request.options = form

        def cb(iq):
            subscription = Subscription.fromElement(iq.pubsub.subscription)

            if subscription.state == "pending":
                raise SubscriptionPending()
            elif subscription.state == "unconfigured":
                raise SubscriptionUnconfigured()
            else:
                # we assume subscription == 'subscribed'
                # any other value would be invalid, but that should have
                # yielded a stanza error.
                return subscription

        d = request.send(self.xmlstream)
        d.addCallback(cb)
        return d

    def unsubscribe(
        self,
        service,
        nodeIdentifier,
        subscriber,
        subscriptionIdentifier=None,
        sender=None,
    ):
        """
        Unsubscribe from a publish subscribe node.

        @param service: The publish subscribe service that keeps the node.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{str}

        @param subscriber: The entity to unsubscribe from the node.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param subscriptionIdentifier: Optional subscription identifier.
        @type subscriptionIdentifier: L{str}
        """
        request = self._request_class("unsubscribe")
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.subscriber = subscriber
        request.subscriptionIdentifier = subscriptionIdentifier
        request.sender = sender
        return request.send(self.xmlstream)

    def publish(self, service, nodeIdentifier, items=None, sender=None, options=None):
        """
        Publish to a publish subscribe node.

        @param service: The publish subscribe service that keeps the node.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{str}
        @param items: Optional list of L{Item}s to publish.
        @type items: L{list}
        @param options: Optional publish-options form (see XEP-0060 ยง7.1.5)
        @type options: C{dict}
        """
        request = self._request_class("publish")
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.items = items
        if options:
            form = data_form.Form(
                formType="submit", formNamespace=NS_PUBSUB_PUBLISH_OPTIONS
            )
            form.makeFields(options)
            request.options = form
        request.sender = sender
        return request.send(self.xmlstream)

    def items(
        self,
        service,
        nodeIdentifier,
        maxItems=None,
        subscriptionIdentifier=None,
        sender=None,
        itemIdentifiers=None,
        orderBy=None,
    ):
        """
        Retrieve previously published items from a publish subscribe node.

        @param service: The publish subscribe service that keeps the node.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{str}

        @param maxItems: Optional limit on the number of retrieved items.
        @type maxItems: L{int}

        @param subscriptionIdentifier: Optional subscription identifier. In
            case the node has been subscribed to multiple times, this narrows
            the results to the specific subscription.
        @type subscriptionIdentifier: L{str}

        @param itemIdentifiers: Identifiers of the items to be retrieved.
        @type itemIdentifiers: L{set} of L{str}

        @param orderBy: Keys to order by
        @type orderBy: L{list} of L{unicode}
        """
        request = self._request_class("items")
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        if maxItems:
            request.maxItems = str(int(maxItems))
        request.subscriptionIdentifier = subscriptionIdentifier
        request.sender = sender
        request.itemIdentifiers = itemIdentifiers
        request.orderBy = orderBy

        def cb(iq):
            items = []
            for element in iq.pubsub.items.elements():
                if element.uri == NS_PUBSUB and element.name == "item":
                    items.append(element)
            return items

        d = request.send(self.xmlstream)
        d.addCallback(cb)
        return d

    def retractItems(
        self, service, nodeIdentifier, itemIdentifiers, notify=None, sender=None
    ):
        """
        Retract items from a publish subscribe node.

        @param service: The publish subscribe service to delete the node from.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: C{unicode}
        @param itemIdentifiers: Identifiers of the items to be retracted.
        @type itemIdentifiers: C{set}
        @param notify: True if notification is required
        @type notify: C{unicode}
        """
        request = self._request_class("retract")
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.itemIdentifiers = itemIdentifiers
        request.notify = notify
        request.sender = sender
        return request.send(self.xmlstream)

    def getOptions(
        self,
        service,
        nodeIdentifier,
        subscriber,
        subscriptionIdentifier=None,
        sender=None,
    ):
        """
        Get subscription options.

        @param service: The publish subscribe service that keeps the node.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{str}

        @param subscriber: The entity subscribed to the node.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param subscriptionIdentifier: Optional subscription identifier.
        @type subscriptionIdentifier: L{str}

        @rtype: L{data_form.Form}
        """
        request = self._request_class("optionsGet")
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.subscriber = subscriber
        request.subscriptionIdentifier = subscriptionIdentifier
        request.sender = sender

        def cb(iq):
            form = data_form.findForm(iq.pubsub.options, NS_PUBSUB_SUBSCRIBE_OPTIONS)
            form.typeCheck()
            return form

        d = request.send(self.xmlstream)
        d.addCallback(cb)
        return d

    def setOptions(
        self,
        service,
        nodeIdentifier,
        subscriber,
        options,
        subscriptionIdentifier=None,
        sender=None,
    ):
        """
        Set subscription options.

        @param service: The publish subscribe service that keeps the node.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param nodeIdentifier: The identifier of the node.
        @type nodeIdentifier: L{str}

        @param subscriber: The entity subscribed to the node.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}

        @param options: Subscription options.
        @type options: L{dict}.

        @param subscriptionIdentifier: Optional subscription identifier.
        @type subscriptionIdentifier: L{str}
        """
        request = self._request_class("optionsSet")
        request.recipient = service
        request.nodeIdentifier = nodeIdentifier
        request.subscriber = subscriber
        request.subscriptionIdentifier = subscriptionIdentifier
        request.sender = sender

        form = data_form.Form(
            formType="submit", formNamespace=NS_PUBSUB_SUBSCRIBE_OPTIONS
        )
        form.makeFields(options)
        request.options = form

        d = request.send(self.xmlstream)
        return d


@implementer(IPubSubService, disco.IDisco)
class PubSubService(XMPPHandler, IQHandlerMixin):
    """
    Protocol implementation for a XMPP Publish Subscribe Service.

    The word Service here is used as taken from the Publish Subscribe
    specification. It is the party responsible for keeping nodes and their
    subscriptions, and sending out notifications.

    Methods from the L{IPubSubService} interface that are called as a result
    of an XMPP request may raise exceptions. Alternatively the deferred
    returned by these methods may have their errback called. These are handled
    as follows:

     - If the exception is an instance of L{error.StanzaError}, an error
       response iq is returned.
     - Any other exception is reported using L{log.msg}. An error response
       with the condition C{internal-server-error} is returned.

    The default implementation of said methods raises an L{Unsupported}
    exception and are meant to be overridden.

    @ivar discoIdentity: Service discovery identity as a dictionary with
                         keys C{'category'}, C{'type'} and C{'name'}.
    @ivar pubSubFeatures: List of supported publish-subscribe features for
                          service discovery, as L{str}.
    @type pubSubFeatures: L{list} or L{None}
    """

    iqHandlers = {
        "/*": "_onPubSubRequest",
    }

    _legacyHandlers = {
        "publish": ("publish", ["sender", "recipient", "nodeIdentifier", "items"]),
        "subscribe": (
            "subscribe",
            ["sender", "recipient", "nodeIdentifier", "subscriber"],
        ),
        "unsubscribe": (
            "unsubscribe",
            ["sender", "recipient", "nodeIdentifier", "subscriber"],
        ),
        "subscriptions": ("subscriptions", ["sender", "recipient"]),
        "affiliations": ("affiliations", ["sender", "recipient"]),
        "create": ("create", ["sender", "recipient", "nodeIdentifier"]),
        "getConfigurationOptions": ("getConfigurationOptions", []),
        "default": ("getDefaultConfiguration", ["sender", "recipient", "nodeType"]),
        "configureGet": ("getConfiguration", ["sender", "recipient", "nodeIdentifier"]),
        "configureSet": (
            "setConfiguration",
            ["sender", "recipient", "nodeIdentifier", "options"],
        ),
        "items": (
            "items",
            ["sender", "recipient", "nodeIdentifier", "maxItems", "itemIdentifiers"],
        ),
        "retract": (
            "retract",
            ["sender", "recipient", "nodeIdentifier", "itemIdentifiers"],
        ),
        "purge": ("purge", ["sender", "recipient", "nodeIdentifier"]),
        "delete": ("delete", ["sender", "recipient", "nodeIdentifier"]),
    }

    _request_class = PubSubRequest

    hideNodes = False

    def __init__(self, resource=None):
        self.resource = resource
        self.discoIdentity = {
            "category": "pubsub",
            "type": "service",
            "name": "Generic Publish-Subscribe Service",
        }

        self.pubSubFeatures = []

    def connectionMade(self):
        self.xmlstream.addObserver(PUBSUB_REQUEST, self.handleRequest)

    def getDiscoInfo(self, requestor, target, nodeIdentifier=""):
        def toInfo(nodeInfo):
            if not nodeInfo:
                return

            nodeType, metaData = nodeInfo["type"], nodeInfo["meta-data"]
            info.append(disco.DiscoIdentity("pubsub", nodeType))
            if metaData:
                form = data_form.Form(
                    formType="result", formNamespace=NS_PUBSUB_META_DATA
                )
                form.addField(
                    data_form.Field(
                        var="pubsub#node_type",
                        value=nodeType,
                        label="The type of node (collection or leaf)",
                    )
                )

                for metaDatum in metaData:
                    form.addField(data_form.Field.fromDict(metaDatum))

                info.append(form)

            return

        info = []

        request = self._request_class("discoInfo")

        if self.resource is not None:
            resource = self.resource.locateResource(request)
            identity = resource.discoIdentity
            features = resource.features
            getInfo = resource.getInfo
        else:
            category = self.discoIdentity["category"]
            idType = self.discoIdentity["type"]
            name = self.discoIdentity["name"]
            identity = disco.DiscoIdentity(category, idType, name)
            features = self.pubSubFeatures
            getInfo = self.getNodeInfo

        if not nodeIdentifier:
            info.append(identity)
            info.append(disco.DiscoFeature(disco.NS_DISCO_ITEMS))
            info.extend(
                [
                    disco.DiscoFeature("%s#%s" % (NS_PUBSUB, feature))
                    for feature in features
                ]
            )

        d = defer.maybeDeferred(getInfo, requestor, target, nodeIdentifier or "")
        d.addCallback(toInfo)
        d.addErrback(log.err)
        d.addCallback(lambda _: info)
        return d

    def _parseNodes(self, nodes, target):
        """parse return values of resource.getNodes

        basestring values are used as node
        tuple are unpacked as node, name
        """
        items = []
        for node in nodes:
            if not node:
                continue
            elif isinstance(node, str):
                items.append(disco.DiscoItem(target, node))
            else:
                _node, name = node
                items.append(disco.DiscoItem(target, _node, name))
        return items

    def getDiscoItems(self, requestor, target, nodeIdentifier=""):
        if self.hideNodes:
            d = defer.succeed([])
        elif self.resource is not None:
            request = self._request_class("discoInfo")
            resource = self.resource.locateResource(request)
            d = resource.getNodes(requestor, target, nodeIdentifier)
        elif nodeIdentifier:
            d = defer.maybeDeferred(self.getNodes, requestor, target)
        else:
            d = defer.succeed([])

        d.addCallback(self._parseNodes, target)
        return d

    def _onPubSubRequest(self, iq):
        request = self._request_class.fromElement(iq)

        if self.resource is not None:
            resource = self.resource.locateResource(request)
        else:
            resource = self

        # Preprocess the request, knowing the handling resource
        try:
            preProcessor = getattr(self, "_preProcess_%s" % request.verb)
        except AttributeError:
            pass
        else:
            request = preProcessor(resource, request)
            if request is None:
                return defer.succeed(None)

        # Process the request itself,
        if resource is not self:
            try:
                handler = getattr(resource, request.verb)
            except AttributeError:
                text = "Request verb: %s" % request.verb
                return defer.fail(Unsupported("", text))

            d = handler(request)
        else:
            try:
                handlerName, argNames = self._legacyHandlers[request.verb]
            except KeyError:
                text = "Request verb: %s" % request.verb
                return defer.fail(Unsupported("", text))

            handler = getattr(self, handlerName)
            args = [getattr(request, arg) for arg in argNames]
            d = handler(*args)

        # If needed, translate the result into a response
        try:
            cb = getattr(self, "_toResponse_%s" % request.verb)
        except AttributeError:
            pass
        else:
            d.addCallback(cb, resource, request)

        return d

    def _toResponse_subscribe(
        self, result: Subscription, resource: "PubSubResource", request: PubSubRequest
    ) -> domish.Element:
        response = domish.Element((NS_PUBSUB, "pubsub"))
        response.addChild(result.toElement(NS_PUBSUB))
        return response

    def _toResponse_unsubscribe(
        self,
        result: Optional[Subscription],
        resource: "PubSubResource",
        request: PubSubRequest,
    ) -> domish.Element:
        response = domish.Element((NS_PUBSUB, "pubsub"))
        if result is None:
            result = Subscription(request.nodeIdentifier, request.subscriber, "none")
        response.addChild(result.toElement(NS_PUBSUB))
        return response

    def _toResponse_subscriptions(self, result, resource, request):
        response = domish.Element((NS_PUBSUB, "pubsub"))
        subscriptions = response.addElement("subscriptions")
        for subscription in result:
            subscriptions.addChild(subscription.toElement(NS_PUBSUB))
        return response

    def _toResponse_affiliations(self, result, resource, request):
        response = domish.Element((NS_PUBSUB, "pubsub"))
        affiliations = response.addElement("affiliations")

        for nodeIdentifier, affiliation in result:
            item = affiliations.addElement("affiliation")
            item["node"] = nodeIdentifier
            item["affiliation"] = affiliation

        return response

    def _toResponse_create(self, result, resource, request):
        if not request.nodeIdentifier or request.nodeIdentifier != result:
            response = domish.Element((NS_PUBSUB, "pubsub"))
            create = response.addElement("create")
            create["node"] = result
            return response
        else:
            return None

    def _formFromConfiguration(self, resource, values):
        fieldDefs = resource.getConfigurationOptions()
        form = data_form.Form(formType="form", formNamespace=NS_PUBSUB_NODE_CONFIG)
        form.makeFields(values, fieldDefs)
        return form

    def _checkConfiguration(self, resource, form):
        fieldDefs = resource.getConfigurationOptions()
        form.typeCheck(fieldDefs, filterUnknown=True)

    def _preProcess_create(self, resource, request):
        if request.options:
            self._checkConfiguration(resource, request.options)
        return request

    def _preProcess_default(self, resource, request):
        if request.nodeType not in ("leaf", "collection"):
            raise error.StanzaError("not-acceptable")
        else:
            return request

    def _toResponse_default(self, options, resource, request):
        response = domish.Element((NS_PUBSUB_OWNER, "pubsub"))
        default = response.addElement("default")
        form = self._formFromConfiguration(resource, options)
        default.addChild(form.toElement())
        return response

    def _toResponse_configureGet(self, options, resource, request):
        response = domish.Element((NS_PUBSUB_OWNER, "pubsub"))
        configure = response.addElement("configure")
        form = self._formFromConfiguration(resource, options)
        configure.addChild(form.toElement())

        if request.nodeIdentifier:
            configure["node"] = request.nodeIdentifier

        return response

    def _preProcess_configureSet(self, resource, request):
        if request.options.formType == "cancel":
            return None
        else:
            self._checkConfiguration(resource, request.options)
            return request

    def _toResponse_items(self, result, resource, request):
        response = domish.Element((NS_PUBSUB, "pubsub"))
        items = response.addElement("items")
        items["node"] = request.nodeIdentifier

        for item in result:
            item.uri = NS_PUBSUB
            items.addChild(item)

        return response

    def _toResponse_subscriptionsGet(self, result, resource, request):
        response = domish.Element((NS_PUBSUB_OWNER, "pubsub"))
        subscriptions = response.addElement("subscriptions")
        subscriptions["node"] = request.nodeIdentifier
        for subscription in result:
            subscription_element = subscription.toElement(NS_PUBSUB)
            del subscription_element["node"]
            subscriptions.addChild(subscription_element)
        return response

    def _createNotification(
        self, eventType, service, nodeIdentifier, subscriber, subscriptions=None
    ):
        headers = []

        if subscriptions:
            for subscription in subscriptions:
                if nodeIdentifier != subscription.nodeIdentifier:
                    headers.append(("Collection", subscription.nodeIdentifier))

        message = domish.Element((None, "message"))
        message["from"] = service.full()
        message["to"] = subscriber.full()
        event = message.addElement((NS_PUBSUB_EVENT, "event"))

        element = event.addElement(eventType)
        element["node"] = nodeIdentifier

        if headers:
            message.addChild(shim.Headers(headers))

        return message

    def _toResponse_affiliationsGet(self, result, resource, request):
        response = domish.Element((NS_PUBSUB_OWNER, "pubsub"))
        affiliations = response.addElement("affiliations")

        if request.nodeIdentifier:
            affiliations["node"] = request.nodeIdentifier

        for entity, affiliation in result.items():
            item = affiliations.addElement("affiliation")
            item["jid"] = entity.full()
            item["affiliation"] = affiliation

        return response

    # public methods

    def notifyPublish(self, service, nodeIdentifier, notifications):
        for subscriber, subscriptions, items in notifications:
            message = self._createNotification(
                "items", service, nodeIdentifier, subscriber, subscriptions
            )
            for item in items:
                item.uri = NS_PUBSUB_EVENT
                message.event.items.addChild(item)
            self.send(message)

    def notifyRetract(self, service, nodeIdentifier, notifications):
        for subscriber, subscriptions, items in notifications:
            message = self._createNotification(
                "items", service, nodeIdentifier, subscriber, subscriptions
            )
            for item in items:
                retract = domish.Element((NS_PUBSUB_EVENT, "retract"))
                retract["id"] = item["id"]
                message.event.items.addChild(retract)
            self.send(message)

    def notifyPurge(self, service, nodeIdentifier, subscribers):
        for subscriber in subscribers:
            message = self._createNotification(
                "purge", service, nodeIdentifier, subscriber
            )
            self.send(message)

    def notifyDelete(self, service, nodeIdentifier, subscribers, redirectURI=None):
        for subscriber in subscribers:
            message = self._createNotification(
                "delete", service, nodeIdentifier, subscriber
            )
            if redirectURI:
                redirect = message.event.delete.addElement("redirect")
                redirect["uri"] = redirectURI
            self.send(message)

    def getNodeInfo(self, requestor, service, nodeIdentifier):
        return None

    def getNodes(self, requestor, service):
        return []

    def publish(self, requestor, service, nodeIdentifier, items, options=None):
        raise Unsupported("publish")

    def subscribe(self, requestor, service, nodeIdentifier, subscriber):
        raise Unsupported("subscribe")

    def unsubscribe(self, requestor, service, nodeIdentifier, subscriber):
        raise Unsupported("subscribe")

    def subscriptions(self, requestor, service):
        raise Unsupported("retrieve-subscriptions")

    def affiliations(self, requestor, service):
        raise Unsupported("retrieve-affiliations")

    def create(self, requestor, service, nodeIdentifier):
        raise Unsupported("create-nodes")

    def getConfigurationOptions(self):
        return {}

    def getDefaultConfiguration(self, requestor, service, nodeType):
        raise Unsupported("retrieve-default")

    def getConfiguration(self, requestor, service, nodeIdentifier):
        raise Unsupported("config-node")

    def setConfiguration(self, requestor, service, nodeIdentifier, options):
        raise Unsupported("config-node")

    def items(self, requestor, service, nodeIdentifier, maxItems, itemIdentifiers):
        raise Unsupported("retrieve-items")

    def retract(self, requestor, service, nodeIdentifier, itemIdentifiers):
        raise Unsupported("retract-items")

    def purge(self, requestor, service, nodeIdentifier):
        raise Unsupported("purge-nodes")

    def delete(self, requestor, service, nodeIdentifier):
        raise Unsupported("delete-nodes")


@implementer(IPubSubResource)
class PubSubResource(object):

    features = []
    discoIdentity = disco.DiscoIdentity("pubsub", "service", "Publish-Subscribe Service")

    def locateResource(self, request):
        return self

    def getInfo(self, requestor, service, nodeIdentifier):
        return defer.succeed(None)

    def getNodes(self, requestor, service, nodeIdentifier):
        return defer.succeed([])

    def getConfigurationOptions(self):
        return {}

    def publish(self, request):
        return defer.fail(Unsupported("publish"))

    def subscribe(self, request):
        return defer.fail(Unsupported("subscribe"))

    def unsubscribe(self, request):
        return defer.fail(Unsupported("subscribe"))

    def subscriptions(self, request):
        return defer.fail(Unsupported("retrieve-subscriptions"))

    def affiliations(self, request):
        return defer.fail(Unsupported("retrieve-affiliations"))

    def create(self, request):
        return defer.fail(Unsupported("create-nodes"))

    def default(self, request):
        return defer.fail(Unsupported("retrieve-default"))

    def configureGet(self, request):
        return defer.fail(Unsupported("config-node"))

    def configureSet(self, request):
        return defer.fail(Unsupported("config-node"))

    def items(self, request):
        return defer.fail(Unsupported("retrieve-items"))

    def retract(self, request):
        return defer.fail(Unsupported("retract-items"))

    def purge(self, request):
        return defer.fail(Unsupported("purge-nodes"))

    def delete(self, request):
        return defer.fail(Unsupported("delete-nodes"))

    def affiliationsGet(self, request):
        return defer.fail(Unsupported("modify-affiliations"))

    def affiliationsSet(self, request):
        return defer.fail(Unsupported("modify-affiliations"))

    def subscriptionsGet(self, request):
        return defer.fail(Unsupported("manage-subscriptions"))

    def subscriptionsSet(self, request):
        return defer.fail(Unsupported("manage-subscriptions"))