Debian Codegraph @

tx_xmpp/pubsub.py

raw
1 # -*- test-case-name: tx_xmpp.test.test.test_pubsub -*-
2 #
3 # Copyright (c) Ralph Meijer, 2007-2021
4 # Copyright (c) Adrien Cossa, 2016
5 # Copyright (c) Jérôme Poisson, 2017-2026
6 # See LICENSE for details.
7
8 """
9 XMPP publish-subscribe protocol.
10
11 This protocol is specified in
12 U{XEP-0060<http://xmpp.org/extensions/xep-0060.html>}.
13 """
14
15 from typing import TYPE_CHECKING, Literal, Self
16
17 from twisted.internet import defer
18 from twisted.python import log
19 from twisted.words.protocols.jabber import error, jid
20 from twisted.words.xish import domish
21 from zope.interface import implementer
22
23 from . import data_form, disco, generic, shim
24 from .compat import IQ
25 from .itx_xmpp import IPubSubClient, IPubSubResource, IPubSubService
26 from .subprotocols import IQHandlerMixin, XMPPHandler
27
28 if TYPE_CHECKING:
29 from . import rsm
30
31 # Iq get and set XPath queries
32 IQ_GET = '/iq[@type="get"]'
33 IQ_SET = '/iq[@type="set"]'
34
35 # Publish-subscribe namespaces
36 NS_PUBSUB = "http://jabber.org/protocol/pubsub"
37 NS_PUBSUB_EVENT = NS_PUBSUB + "#event"
38 NS_PUBSUB_ERRORS = NS_PUBSUB + "#errors"
39 NS_PUBSUB_OWNER = NS_PUBSUB + "#owner"
40 NS_PUBSUB_NODE_CONFIG = NS_PUBSUB + "#node_config"
41 NS_PUBSUB_META_DATA = NS_PUBSUB + "#meta-data"
42 NS_PUBSUB_SUBSCRIBE_OPTIONS = NS_PUBSUB + "#subscribe_options"
43 NS_PUBSUB_PUBLISH_OPTIONS = NS_PUBSUB + "#publish-options"
44
45 NS_ORDER_BY = "urn:xmpp:order-by:0"
46
47 # XPath to match pubsub requests
48 PUBSUB_REQUEST = (
49 '/iq[@type="get" or @type="set"]/'
50 + 'pubsub[@xmlns="'
51 + NS_PUBSUB
52 + '" or '
53 + '@xmlns="'
54 + NS_PUBSUB_OWNER
55 + '"]'
56 )
57
58 BOOL_TRUE = ("1", "true")
59 BOOL_FALSE = ("0", "false")
60
61
62 class SubscriptionPending(Exception):
63 """
64 Raised when the requested subscription is pending acceptance.
65 """
66
67
68 class SubscriptionUnconfigured(Exception):
69 """
70 Raised when the requested subscription needs to be configured before
71 becoming active.
72 """
73
74
75 class PubSubError(error.StanzaError):
76 """
77 Exception with publish-subscribe specific condition.
78 """
79
80 def __init__(self, condition, pubsubCondition, feature=None, text=None):
81 appCondition = domish.Element((NS_PUBSUB_ERRORS, pubsubCondition))
82 if feature:
83 appCondition["feature"] = feature
84 error.StanzaError.__init__(self, condition, text=text, appCondition=appCondition)
85
86
87 class BadRequest(error.StanzaError):
88 """
89 Bad request stanza error.
90 """
91
92 def __init__(self, pubsubCondition=None, text=None):
93 if pubsubCondition:
94 appCondition = domish.Element((NS_PUBSUB_ERRORS, pubsubCondition))
95 else:
96 appCondition = None
97 error.StanzaError.__init__(
98 self, "bad-request", text=text, appCondition=appCondition
99 )
100
101
102 class Unsupported(PubSubError):
103 def __init__(self, feature, text=None):
104 self.feature = feature
105 PubSubError.__init__(
106 self, "feature-not-implemented", "unsupported", feature, text
107 )
108
109 def __str__(self):
110 message = PubSubError.__str__(self)
111 message += ", feature %r" % self.feature
112 return message
113
114
115 class Subscription:
116 """
117 A subscription to a node.
118
119 @ivar nodeIdentifier: The identifier of the node subscribed to. The root
120 node is denoted by L{None}.
121
122 @ivar subscriber: The subscribing entity.
123
124 @ivar state: The subscription state. One of C{'subscribed'}, C{'pending'},
125 C{'unconfigured'}, C{'none'}.
126
127 @ivar options: Optional list of subscription options.
128
129 @ivar subscriptionIdentifier: Optional subscription identifier.
130 """
131
132 def __init__(
133 self,
134 nodeIdentifier: str | None,
135 subscriber: jid.JID | None,
136 state: Literal["subscribed", "pending", "unconfigured", "none"] | None,
137 options: dict | None = None,
138 subscriptionIdentifier: str | None = None,
139 ) -> None:
140 self.nodeIdentifier = nodeIdentifier
141 self.subscriber = subscriber
142 self.state = state
143 self.options = options or {}
144 self.subscriptionIdentifier = subscriptionIdentifier
145
146 @staticmethod
147 def fromElement(element: domish.Element) -> "Subscription":
148 return Subscription(
149 element.getAttribute("node"),
150 jid.JID(element.getAttribute("jid")),
151 element.getAttribute("subscription"),
152 subscriptionIdentifier=element.getAttribute("subid"),
153 )
154
155 def toElement(self, defaultUri: str | None = None) -> domish.Element:
156 """
157 Return the DOM representation of this subscription.
158
159 @rtype: L{domish.Element}
160 """
161 element = domish.Element((defaultUri, "subscription"))
162 if self.nodeIdentifier:
163 element["node"] = self.nodeIdentifier
164 element["jid"] = str(self.subscriber)
165 element["subscription"] = self.state
166 if self.subscriptionIdentifier:
167 element["subid"] = self.subscriptionIdentifier
168 return element
169
170
171 class Item(domish.Element):
172 """
173 Publish subscribe item.
174
175 This behaves like an object providing L{domish.IElement}.
176
177 Item payload can be added using C{addChild} or C{addRawXml}, or using the
178 C{payload} keyword argument to C{__init__}.
179 """
180
181 def __init__(self, id=None, payload=None):
182 """
183 @param id: optional item identifier
184 @type id: L{str}
185 @param payload: optional item payload. Either as a domish element, or
186 as serialized XML.
187 @type payload: object providing L{domish.IElement} or L{str}.
188 """
189
190 domish.Element.__init__(self, (None, "item"))
191 if id is not None:
192 self["id"] = id
193 if payload is not None:
194 if isinstance(payload, str):
195 self.addRawXml(payload)
196 else:
197 self.addChild(payload)
198
199
200 class PubSubRequest(generic.Stanza):
201 """
202 A publish-subscribe request.
203
204 The set of instance variables used depends on the type of request. If
205 a variable is not applicable or not passed in the request, its value is
206 L{None}.
207
208 @ivar verb: The type of publish-subscribe request. See C{_requestVerbMap}.
209
210 @ivar affiliations: Affiliations to be modified, as a dictionary of entity
211 (L{JID<twisted.words.protocols.jabber.jid.JID>} to affiliation
212 (L{str}).
213
214 @ivar items: The items to be published, as L{domish.Element}s.
215
216 @ivar itemIdentifiers: Identifiers of the items to be retrieved or
217 retracted.
218
219 @ivar maxItems: Maximum number of items to retrieve.
220
221 @ivar nodeIdentifier: Identifier of the node the request is about.
222
223 @ivar nodeType: The type of node that should be created, or for which the
224 configuration is retrieved. C{'leaf'} or C{'collection'}.
225
226 @ivar options: Configurations options for nodes, subscriptions and publish
227 requests.
228
229 @ivar subscriber: The subscribing entity.
230
231 @ivar subscriptionIdentifier: Identifier for a specific subscription.
232
233 @ivar subscriptions: Subscriptions to be modified, as a set of
234 L{Subscription}.
235
236 @ivar notify: Whether to notify subscribers of retracted items.
237
238 @ivar orderBy: List of order-by attributes for items retrieval.
239 """
240
241 verb: str | None = None
242
243 affiliations: dict[jid.JID, str] | None = None
244 items: list[domish.Element] | None = None
245 itemIdentifiers: list[str] | None = None
246 maxItems: int | None = None
247 nodeIdentifier: str | None = None
248 nodeType: str | None = None
249 options: data_form.Form | None = None
250 subscriber: jid.JID | None = None
251 subscriptionIdentifier: str | None = None
252 subscriptions: set[Subscription] | None = None
253 notify: bool | None = None
254 orderBy: list[str] | None = None
255
256 # Map request iq type and subelement name to request verb
257 _requestVerbMap = {
258 ("set", NS_PUBSUB, "publish"): "publish",
259 ("set", NS_PUBSUB, "subscribe"): "subscribe",
260 ("set", NS_PUBSUB, "unsubscribe"): "unsubscribe",
261 ("get", NS_PUBSUB, "options"): "optionsGet",
262 ("set", NS_PUBSUB, "options"): "optionsSet",
263 ("get", NS_PUBSUB, "subscriptions"): "subscriptions",
264 ("get", NS_PUBSUB, "affiliations"): "affiliations",
265 ("set", NS_PUBSUB, "create"): "create",
266 ("get", NS_PUBSUB_OWNER, "default"): "default",
267 ("get", NS_PUBSUB_OWNER, "configure"): "configureGet",
268 ("set", NS_PUBSUB_OWNER, "configure"): "configureSet",
269 ("get", NS_PUBSUB, "items"): "items",
270 ("set", NS_PUBSUB, "retract"): "retract",
271 ("set", NS_PUBSUB_OWNER, "purge"): "purge",
272 ("set", NS_PUBSUB_OWNER, "delete"): "delete",
273 ("get", NS_PUBSUB_OWNER, "affiliations"): "affiliationsGet",
274 ("set", NS_PUBSUB_OWNER, "affiliations"): "affiliationsSet",
275 ("get", NS_PUBSUB_OWNER, "subscriptions"): "subscriptionsGet",
276 ("set", NS_PUBSUB_OWNER, "subscriptions"): "subscriptionsSet",
277 }
278
279 # Map request verb to request iq type and subelement name
280 _verbRequestMap = dict(((v, k) for k, v in _requestVerbMap.items()))
281
282 # Map request verb to parameter handler names
283 _parameters = {
284 "publish": ["node", "items", "publishOptionsOrNone"],
285 "subscribe": ["nodeOrEmpty", "jid", "optionsWithSubscribe"],
286 "unsubscribe": ["nodeOrEmpty", "jid", "subidOrNone"],
287 "optionsGet": ["nodeOrEmpty", "jid", "subidOrNone"],
288 "optionsSet": ["nodeOrEmpty", "jid", "options", "subidOrNone"],
289 "subscriptions": ["nodeOrNone"],
290 "affiliations": ["nodeOrNone"],
291 "create": ["nodeOrNone", "configureOrNone"],
292 "default": ["default"],
293 "configureGet": ["nodeOrEmpty"],
294 "configureSet": ["nodeOrEmpty", "configureOrNone"],
295 "items": ["node", "maxItems", "itemIdentifiers", "subidOrNone", "orderBy"],
296 "retract": ["node", "notify", "itemIdentifiers"],
297 "purge": ["node"],
298 "delete": ["node"],
299 "affiliationsGet": ["nodeOrNone"],
300 "affiliationsSet": ["node", "affiliations"],
301 "subscriptionsGet": ["nodeOrNone"],
302 "subscriptionsSet": ["node", "subscriptions"],
303 }
304
305 def __init__(self, verb=None):
306 self.verb = verb
307
308 def _parse_node(self, verbElement):
309 """
310 Parse the required node identifier out of the verbElement.
311 """
312 try:
313 self.nodeIdentifier = verbElement["node"]
314 except KeyError:
315 raise BadRequest("nodeid-required")
316
317 def _render_node(self, verbElement):
318 """
319 Render the required node identifier on the verbElement.
320 """
321 if not self.nodeIdentifier:
322 raise Exception("Node identifier is required")
323
324 verbElement["node"] = self.nodeIdentifier
325
326 def _parse_nodeOrEmpty(self, verbElement):
327 """
328 Parse the node identifier out of the verbElement. May be empty.
329 """
330 self.nodeIdentifier = verbElement.getAttribute("node", "")
331
332 def _render_nodeOrEmpty(self, verbElement):
333 """
334 Render the node identifier on the verbElement. May be empty.
335 """
336 if self.nodeIdentifier:
337 verbElement["node"] = self.nodeIdentifier
338
339 def _parse_nodeOrNone(self, verbElement):
340 """
341 Parse the optional node identifier out of the verbElement.
342 """
343 self.nodeIdentifier = verbElement.getAttribute("node")
344
345 def _render_nodeOrNone(self, verbElement):
346 """
347 Render the optional node identifier on the verbElement.
348 """
349 if self.nodeIdentifier:
350 verbElement["node"] = self.nodeIdentifier
351
352 def _parse_items(self, verbElement):
353 """
354 Parse items out of the verbElement for publish requests.
355 """
356 self.items = []
357 for element in verbElement.elements():
358 if element.uri == NS_PUBSUB and element.name == "item":
359 self.items.append(element)
360
361 def _render_items(self, verbElement):
362 """
363 Render items into the verbElement for publish requests.
364 """
365 if self.items:
366 for item in self.items:
367 item.uri = NS_PUBSUB
368 verbElement.addChild(item)
369
370 def _parse_publishOptionsOrNone(self, verbElement):
371 """
372 Parse optional publish-options form in publish request.
373 """
374 for element in verbElement.parent.elements():
375 form = data_form.findForm(element, NS_PUBSUB_PUBLISH_OPTIONS)
376 if form is not None:
377 if form.formType != "submit":
378 raise BadRequest(text="Unexpected form type '%s'" % form.formType)
379 else:
380 form = data_form.Form("submit", formNamespace=NS_PUBSUB_PUBLISH_OPTIONS)
381
382 self.options = form
383
384 def _render_publishOptionsOrNone(self, verbElement):
385 if self.options is not None:
386 if self.options.formType != "submit":
387 log.err(
388 "Invalid type for publish-options form ({formType}): {xml}".format(
389 formType=self.options.formType, xml=verbElement.toXml()
390 )
391 )
392 return
393 publishOptions = verbElement.parent.addElement("publish-options")
394 publishOptions.addChild(self.options.toElement())
395
396 def _parse_jid(self, verbElement):
397 """
398 Parse subscriber out of the verbElement for un-/subscribe requests.
399 """
400 try:
401 self.subscriber = jid.internJID(verbElement["jid"])
402 except KeyError:
403 raise BadRequest("jid-required")
404
405 def _render_jid(self, verbElement):
406 """
407 Render subscriber into the verbElement for un-/subscribe requests.
408 """
409 verbElement["jid"] = self.subscriber.full()
410
411 def _parse_default(self, verbElement):
412 """
413 Parse node type out of a request for the default node configuration.
414 """
415 form = data_form.findForm(verbElement, NS_PUBSUB_NODE_CONFIG)
416 if form is not None and form.formType == "submit":
417 values = form.getValues()
418 self.nodeType = values.get("pubsub#node_type", "leaf")
419 else:
420 self.nodeType = "leaf"
421
422 def _parse_configure(self, verbElement):
423 """
424 Parse options out of a request for setting the node configuration.
425 """
426 form = data_form.findForm(verbElement, NS_PUBSUB_NODE_CONFIG)
427 if form is not None:
428 if form.formType in ("submit", "cancel"):
429 self.options = form
430 else:
431 raise BadRequest(text="Unexpected form type '%s'" % form.formType)
432 else:
433 raise BadRequest(text="Missing configuration form")
434
435 def _parse_configureOrNone(self, verbElement):
436 """
437 Parse optional node configuration form in create request.
438 """
439 for element in verbElement.parent.elements():
440 if (
441 element.uri in (NS_PUBSUB, NS_PUBSUB_OWNER)
442 and element.name == "configure"
443 ):
444 form = data_form.findForm(element, NS_PUBSUB_NODE_CONFIG)
445 if form is not None:
446 if form.formType in ("submit", "cancel"):
447 self.options = form
448 else:
449 raise BadRequest(text="Unexpected form type '%s'" % form.formType)
450 else:
451 if self.verb == "create":
452 # Empty <configure/> in create request means use default config
453 self.options = data_form.Form(
454 "submit", formNamespace=NS_PUBSUB_NODE_CONFIG
455 )
456 else:
457 # For configureSet, a form is required
458 raise BadRequest(text="data form is required")
459
460 def _render_configureOrNone(self, verbElement):
461 """
462 Render optional node configuration form in create request.
463 """
464 if self.options is not None:
465 if verbElement.name == "configure":
466 configure = verbElement
467 else:
468 configure = verbElement.parent.addElement("configure")
469 configure.addChild(self.options.toElement())
470
471 def _parse_itemIdentifiers(self, verbElement):
472 """
473 Parse item identifiers out of items and retract requests.
474 """
475 self.itemIdentifiers = []
476 for element in verbElement.elements():
477 if element.uri == NS_PUBSUB and element.name == "item":
478 try:
479 self.itemIdentifiers.append(element["id"])
480 except KeyError:
481 raise BadRequest()
482
483 def _render_itemIdentifiers(self, verbElement):
484 """
485 Render item identifiers into items and retract requests.
486 """
487 if self.itemIdentifiers:
488 for itemIdentifier in self.itemIdentifiers:
489 item = verbElement.addElement("item")
490 item["id"] = itemIdentifier
491
492 def _parse_maxItems(self, verbElement):
493 """
494 Parse maximum items out of an items request.
495 """
496 value = verbElement.getAttribute("max_items")
497
498 if value:
499 try:
500 self.maxItems = int(value)
501 except ValueError:
502 raise BadRequest(
503 text="Field max_items requires a positive " + "integer value"
504 )
505
506 def _render_maxItems(self, verbElement):
507 """
508 Render maximum items into an items request.
509 """
510 if self.maxItems:
511 verbElement["max_items"] = str(self.maxItems)
512
513 def _parse_subidOrNone(self, verbElement):
514 """
515 Parse subscription identifier out of a request.
516 """
517 self.subscriptionIdentifier = verbElement.getAttribute("subid")
518
519 def _render_subidOrNone(self, verbElement):
520 """
521 Render subscription identifier into a request.
522 """
523 if self.subscriptionIdentifier:
524 verbElement["subid"] = self.subscriptionIdentifier
525
526 def _parse_options(self, verbElement):
527 """
528 Parse options form out of a subscription options request.
529 """
530 form = data_form.findForm(verbElement, NS_PUBSUB_SUBSCRIBE_OPTIONS)
531 if form is not None:
532 if form.formType in ("submit", "cancel"):
533 self.options = form
534 else:
535 raise BadRequest(text="Unexpected form type '%s'" % form.formType)
536 else:
537 raise BadRequest(text="Missing options form")
538
539 def _render_options(self, verbElement):
540 verbElement.addChild(self.options.toElement())
541
542 def _parse_optionsWithSubscribe(self, verbElement):
543 for element in verbElement.parent.elements():
544 if element.name == "options" and element.uri == NS_PUBSUB:
545 form = data_form.findForm(element, NS_PUBSUB_SUBSCRIBE_OPTIONS)
546 if form is not None:
547 if form.formType != "submit":
548 raise BadRequest(text="Unexpected form type '%s'" % form.formType)
549 else:
550 form = data_form.Form(
551 "submit", formNamespace=NS_PUBSUB_SUBSCRIBE_OPTIONS
552 )
553 self.options = form
554
555 def _render_optionsWithSubscribe(self, verbElement):
556 if self.options is not None:
557 optionsElement = verbElement.parent.addElement("options")
558 self._render_options(optionsElement)
559
560 def _parse_affiliations(self, verbElement):
561 self.affiliations = {}
562 for element in verbElement.elements():
563 if element.uri == NS_PUBSUB_OWNER and element.name == "affiliation":
564 try:
565 entity = jid.internJID(element["jid"]).userhostJID()
566 except KeyError:
567 raise BadRequest(text="Missing jid attribute")
568
569 if entity in self.affiliations:
570 raise BadRequest(text="Multiple affiliations for an entity")
571
572 try:
573 affiliation = element["affiliation"]
574 except KeyError:
575 raise BadRequest(text="Missing affiliation attribute")
576
577 self.affiliations[entity] = affiliation
578
579 def _render_affiliations(self, verbElement):
580 for entity, affiliation in self.affiliations.items():
581 affiliationElement = verbElement.addElement((NS_PUBSUB_OWNER, "affiliation"))
582 affiliationElement["jid"] = entity.full()
583 affiliationElement["affiliation"] = affiliation
584
585 def _parse_subscriptions(self, verbElement):
586 self.subscriptions = set()
587 seen_entities = set()
588 for element in verbElement.elements():
589 if element.uri == NS_PUBSUB_OWNER and element.name == "subscription":
590 try:
591 subscriber = jid.internJID(element["jid"]).userhostJID()
592 except KeyError:
593 raise BadRequest(text="Missing jid attribute")
594
595 if subscriber in seen_entities:
596 raise BadRequest(text="Multiple subscriptions for an subscriber")
597 seen_entities.add(subscriber)
598
599 try:
600 state = element["subscription"]
601 except KeyError:
602 # §8.8.2.1 says that value MUST NOT be changed
603 # if subscription is missing
604 continue
605
606 self.subscriptions.add(
607 Subscription(self.nodeIdentifier, subscriber, state)
608 )
609
610 def _render_subscriptions(self, verbElement):
611 for subscription in self.subscriptions:
612 subscriptionElement = verbElement.addElement(
613 (NS_PUBSUB_OWNER, "subscription")
614 )
615 subscriptionElement["jid"] = subscription.subscriber.full()
616 subscriptionElement["subscription"] = subscription.state
617
618 def _parse_notify(self, verbElement):
619 value = verbElement.getAttribute("notify")
620
621 if value:
622 if value in BOOL_TRUE:
623 self.notify = True
624 elif value in BOOL_FALSE:
625 self.notify = False
626 else:
627 raise BadRequest(text="Field notify must be a boolean value")
628
629 def _render_notify(self, verbElement):
630 if self.notify is not None:
631 verbElement["notify"] = "true" if self.notify else "false"
632
633 def _parse_orderBy(self, verbElement):
634 pubsub_elt = verbElement.parent
635 self.orderBy = []
636 for element in pubsub_elt.elements(NS_ORDER_BY, "order"):
637 self.orderBy.append(element["by"])
638
639 def _render_orderBy(self, verbElement):
640 if self.orderBy is None:
641 return
642 pubsub_elt = verbElement.parent
643 for by_attr in self.orderBy:
644 order_elt = pubsub_elt.addElement((NS_ORDER_BY, "order"))
645 order_elt["by"] = by_attr
646
647 def parseElement(self, element):
648 """
649 Parse the publish-subscribe verb and parameters out of a request.
650 """
651 generic.Stanza.parseElement(self, element)
652
653 verbs = []
654 verbElements = []
655 for child in element.pubsub.elements():
656 key = (self.stanzaType, child.uri, child.name)
657 try:
658 verb = self._requestVerbMap[key]
659 except KeyError:
660 continue
661
662 verbs.append(verb)
663 verbElements.append(child)
664
665 if not verbs:
666 raise NotImplementedError()
667
668 if len(verbs) > 1:
669 if "optionsSet" in verbs and "subscribe" in verbs:
670 self.verb = "subscribe"
671 verbElement = verbElements[verbs.index("subscribe")]
672 else:
673 raise NotImplementedError()
674 else:
675 self.verb = verbs[0]
676 verbElement = verbElements[0]
677
678 for parameter in self._parameters[self.verb]:
679 getattr(self, "_parse_%s" % parameter)(verbElement)
680
681 def send(self, xs):
682 """
683 Send this request to its recipient.
684
685 This renders all of the relevant parameters for this specific
686 requests into an L{IQ}, and invoke its C{send} method.
687 This returns a deferred that fires upon reception of a response. See
688 L{IQ} for details.
689
690 @param xs: The XML stream to send the request on.
691 @type xs: L{twisted.words.protocols.jabber.xmlstream.XmlStream}
692 @rtype: L{defer.Deferred}.
693 """
694
695 try:
696 self.stanzaType, childURI, childName = self._verbRequestMap[self.verb]
697 except KeyError:
698 raise NotImplementedError()
699
700 iq = IQ(xs, self.stanzaType)
701 iq.addElement((childURI, "pubsub"))
702 verbElement = iq.pubsub.addElement(childName)
703
704 if self.sender:
705 iq["from"] = self.sender.full()
706 if self.recipient:
707 iq["to"] = self.recipient.full()
708
709 for parameter in self._parameters[self.verb]:
710 getattr(self, "_render_%s" % parameter)(verbElement)
711
712 return iq.send()
713
714
715 class PubSubEvent:
716 """
717 A publish subscribe event.
718
719 @param sender: The entity from which the notification was received.
720 @type sender: L{jid.JID}
721 @param recipient: The entity to which the notification was sent.
722 @type recipient: L{tx_xmpp.pubsub.ItemsEvent}
723 @param nodeIdentifier: Identifier of the node the event pertains to.
724 @type nodeIdentifier: L{str}
725 @param headers: SHIM headers, see L{tx_xmpp.shim.extractHeaders}.
726 @type headers: L{dict}
727 """
728
729 def __init__(self, sender, recipient, nodeIdentifier, headers):
730 self.sender = sender
731 self.recipient = recipient
732 self.nodeIdentifier = nodeIdentifier
733 self.headers = headers
734
735
736 class ItemsEvent(PubSubEvent):
737 """
738 A publish-subscribe event that signifies new, updated and retracted items.
739
740 @param items: List of received items as domish elements.
741 @type items: L{list} of L{domish.Element}
742 """
743
744 def __init__(self, sender, recipient, nodeIdentifier, items, headers):
745 PubSubEvent.__init__(self, sender, recipient, nodeIdentifier, headers)
746 self.items = items
747
748
749 class DeleteEvent(PubSubEvent):
750 """
751 A publish-subscribe event that signifies the deletion of a node.
752 """
753
754 redirectURI = None
755
756
757 class PurgeEvent(PubSubEvent):
758 """
759 A publish-subscribe event that signifies the purging of a node.
760 """
761
762
763 @implementer(IPubSubClient)
764 class PubSubClient(XMPPHandler):
765 """
766 Publish subscribe client protocol.
767 """
768
769 _request_class = PubSubRequest
770
771 def connectionInitialized(self):
772 self.xmlstream.addObserver(
773 '/message/event[@xmlns="%s"]' % NS_PUBSUB_EVENT, self._onEvent
774 )
775
776 def _onEvent(self, message):
777 if message.getAttribute("type") == "error":
778 return
779
780 try:
781 sender = jid.JID(message["from"])
782 recipient = jid.JID(message["to"])
783 except KeyError:
784 return
785
786 actionElement = None
787 for element in message.event.elements():
788 if element.uri == NS_PUBSUB_EVENT:
789 actionElement = element
790
791 if not actionElement:
792 return
793
794 eventHandler = getattr(self, "_onEvent_%s" % actionElement.name, None)
795
796 if eventHandler:
797 headers = shim.extractHeaders(message)
798 eventHandler(sender, recipient, actionElement, headers)
799 message.handled = True
800
801 def _onEvent_items(self, sender, recipient, action, headers):
802 nodeIdentifier = action["node"]
803
804 items = [
805 element
806 for element in action.elements()
807 if element.name in ("item", "retract")
808 ]
809
810 event = ItemsEvent(sender, recipient, nodeIdentifier, items, headers)
811 self.itemsReceived(event)
812
813 def _onEvent_delete(self, sender, recipient, action, headers):
814 nodeIdentifier = action["node"]
815 event = DeleteEvent(sender, recipient, nodeIdentifier, headers)
816 if action.redirect:
817 event.redirectURI = action.redirect.getAttribute("uri")
818 self.deleteReceived(event)
819
820 def _onEvent_purge(self, sender, recipient, action, headers):
821 nodeIdentifier = action["node"]
822 event = PurgeEvent(sender, recipient, nodeIdentifier, headers)
823 self.purgeReceived(event)
824
825 def itemsReceived(self, event):
826 pass
827
828 def deleteReceived(self, event):
829 pass
830
831 def purgeReceived(self, event):
832 pass
833
834 def createNode(self, service, nodeIdentifier=None, options=None, sender=None):
835 """
836 Create a publish subscribe node.
837
838 @param service: The publish subscribe service to create the node at.
839 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
840 @param nodeIdentifier: Optional suggestion for the id of the node.
841 @type nodeIdentifier: L{str}
842 @param options: Optional node configuration options.
843 @type options: L{dict}
844 """
845 request = self._request_class("create")
846 request.recipient = service
847 request.nodeIdentifier = nodeIdentifier
848 request.sender = sender
849
850 if options:
851 form = data_form.Form(formType="submit", formNamespace=NS_PUBSUB_NODE_CONFIG)
852 form.makeFields(options)
853 request.options = form
854
855 def cb(iq):
856 try:
857 new_node = iq.pubsub.create["node"]
858 except AttributeError:
859 # the suggested node identifier was accepted
860 new_node = nodeIdentifier
861 return new_node
862
863 d = request.send(self.xmlstream)
864 d.addCallback(cb)
865 return d
866
867 def deleteNode(self, service, nodeIdentifier, sender=None):
868 """
869 Delete a publish subscribe node.
870
871 @param service: The publish subscribe service to delete the node from.
872 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
873 @param nodeIdentifier: The identifier of the node.
874 @type nodeIdentifier: L{str}
875 """
876 request = self._request_class("delete")
877 request.recipient = service
878 request.nodeIdentifier = nodeIdentifier
879 request.sender = sender
880 return request.send(self.xmlstream)
881
882 def subscribe(self, service, nodeIdentifier, subscriber, options=None, sender=None):
883 """
884 Subscribe to a publish subscribe node.
885
886 @param service: The publish subscribe service that keeps the node.
887 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
888
889 @param nodeIdentifier: The identifier of the node.
890 @type nodeIdentifier: L{str}
891
892 @param subscriber: The entity to subscribe to the node. This entity
893 will get notifications of new published items.
894 @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
895
896 @param options: Subscription options.
897 @type options: L{dict}
898
899 @return: Deferred that fires with L{Subscription} or errbacks with
900 L{SubscriptionPending} or L{SubscriptionUnconfigured}.
901 @rtype: L{defer.Deferred}
902 """
903 request = self._request_class("subscribe")
904 request.recipient = service
905 request.nodeIdentifier = nodeIdentifier
906 request.subscriber = subscriber
907 request.sender = sender
908
909 if options:
910 form = data_form.Form(
911 formType="submit", formNamespace=NS_PUBSUB_SUBSCRIBE_OPTIONS
912 )
913 form.makeFields(options)
914 request.options = form
915
916 def cb(iq):
917 subscription = Subscription.fromElement(iq.pubsub.subscription)
918
919 if subscription.state == "pending":
920 raise SubscriptionPending()
921 elif subscription.state == "unconfigured":
922 raise SubscriptionUnconfigured()
923 else:
924 # we assume subscription == 'subscribed'
925 # any other value would be invalid, but that should have
926 # yielded a stanza error.
927 return subscription
928
929 d = request.send(self.xmlstream)
930 d.addCallback(cb)
931 return d
932
933 def unsubscribe(
934 self,
935 service,
936 nodeIdentifier,
937 subscriber,
938 subscriptionIdentifier=None,
939 sender=None,
940 ):
941 """
942 Unsubscribe from a publish subscribe node.
943
944 @param service: The publish subscribe service that keeps the node.
945 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
946
947 @param nodeIdentifier: The identifier of the node.
948 @type nodeIdentifier: L{str}
949
950 @param subscriber: The entity to unsubscribe from the node.
951 @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
952
953 @param subscriptionIdentifier: Optional subscription identifier.
954 @type subscriptionIdentifier: L{str}
955 """
956 request = self._request_class("unsubscribe")
957 request.recipient = service
958 request.nodeIdentifier = nodeIdentifier
959 request.subscriber = subscriber
960 request.subscriptionIdentifier = subscriptionIdentifier
961 request.sender = sender
962 return request.send(self.xmlstream)
963
964 def publish(self, service, nodeIdentifier, items=None, sender=None, options=None):
965 """
966 Publish to a publish subscribe node.
967
968 @param service: The publish subscribe service that keeps the node.
969 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
970 @param nodeIdentifier: The identifier of the node.
971 @type nodeIdentifier: L{str}
972 @param items: Optional list of L{Item}s to publish.
973 @type items: L{list}
974 @param options: Optional publish-options form (see XEP-0060 §7.1.5)
975 @type options: C{dict}
976 """
977 request = self._request_class("publish")
978 request.recipient = service
979 request.nodeIdentifier = nodeIdentifier
980 request.items = items
981 if options:
982 form = data_form.Form(
983 formType="submit", formNamespace=NS_PUBSUB_PUBLISH_OPTIONS
984 )
985 form.makeFields(options)
986 request.options = form
987 request.sender = sender
988 return request.send(self.xmlstream)
989
990 def items(
991 self,
992 service,
993 nodeIdentifier,
994 maxItems=None,
995 subscriptionIdentifier=None,
996 sender=None,
997 itemIdentifiers=None,
998 orderBy=None,
999 ):
1000 """
1001 Retrieve previously published items from a publish subscribe node.
1002
1003 @param service: The publish subscribe service that keeps the node.
1004 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
1005
1006 @param nodeIdentifier: The identifier of the node.
1007 @type nodeIdentifier: L{str}
1008
1009 @param maxItems: Optional limit on the number of retrieved items.
1010 @type maxItems: L{int}
1011
1012 @param subscriptionIdentifier: Optional subscription identifier. In
1013 case the node has been subscribed to multiple times, this narrows
1014 the results to the specific subscription.
1015 @type subscriptionIdentifier: L{str}
1016
1017 @param itemIdentifiers: Identifiers of the items to be retrieved.
1018 @type itemIdentifiers: L{set} of L{str}
1019
1020 @param orderBy: Keys to order by
1021 @type orderBy: L{list} of L{unicode}
1022 """
1023 request = self._request_class("items")
1024 request.recipient = service
1025 request.nodeIdentifier = nodeIdentifier
1026 if maxItems:
1027 request.maxItems = str(int(maxItems))
1028 request.subscriptionIdentifier = subscriptionIdentifier
1029 request.sender = sender
1030 request.itemIdentifiers = itemIdentifiers
1031 request.orderBy = orderBy
1032
1033 def cb(iq):
1034 items = []
1035 for element in iq.pubsub.items.elements():
1036 if element.uri == NS_PUBSUB and element.name == "item":
1037 items.append(element)
1038 return items
1039
1040 d = request.send(self.xmlstream)
1041 d.addCallback(cb)
1042 return d
1043
1044 def retractItems(
1045 self, service, nodeIdentifier, itemIdentifiers, notify=None, sender=None
1046 ):
1047 """
1048 Retract items from a publish subscribe node.
1049
1050 @param service: The publish subscribe service to delete the node from.
1051 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
1052 @param nodeIdentifier: The identifier of the node.
1053 @type nodeIdentifier: C{unicode}
1054 @param itemIdentifiers: Identifiers of the items to be retracted.
1055 @type itemIdentifiers: C{set}
1056 @param notify: True if notification is required
1057 @type notify: C{unicode}
1058 """
1059 request = self._request_class("retract")
1060 request.recipient = service
1061 request.nodeIdentifier = nodeIdentifier
1062 request.itemIdentifiers = itemIdentifiers
1063 request.notify = notify
1064 request.sender = sender
1065 return request.send(self.xmlstream)
1066
1067 def getOptions(
1068 self,
1069 service,
1070 nodeIdentifier,
1071 subscriber,
1072 subscriptionIdentifier=None,
1073 sender=None,
1074 ):
1075 """
1076 Get subscription options.
1077
1078 @param service: The publish subscribe service that keeps the node.
1079 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
1080
1081 @param nodeIdentifier: The identifier of the node.
1082 @type nodeIdentifier: L{str}
1083
1084 @param subscriber: The entity subscribed to the node.
1085 @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
1086
1087 @param subscriptionIdentifier: Optional subscription identifier.
1088 @type subscriptionIdentifier: L{str}
1089
1090 @rtype: L{data_form.Form}
1091 """
1092 request = self._request_class("optionsGet")
1093 request.recipient = service
1094 request.nodeIdentifier = nodeIdentifier
1095 request.subscriber = subscriber
1096 request.subscriptionIdentifier = subscriptionIdentifier
1097 request.sender = sender
1098
1099 def cb(iq):
1100 form = data_form.findForm(iq.pubsub.options, NS_PUBSUB_SUBSCRIBE_OPTIONS)
1101 form.typeCheck()
1102 return form
1103
1104 d = request.send(self.xmlstream)
1105 d.addCallback(cb)
1106 return d
1107
1108 def setOptions(
1109 self,
1110 service,
1111 nodeIdentifier,
1112 subscriber,
1113 options,
1114 subscriptionIdentifier=None,
1115 sender=None,
1116 ):
1117 """
1118 Set subscription options.
1119
1120 @param service: The publish subscribe service that keeps the node.
1121 @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
1122
1123 @param nodeIdentifier: The identifier of the node.
1124 @type nodeIdentifier: L{str}
1125
1126 @param subscriber: The entity subscribed to the node.
1127 @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
1128
1129 @param options: Subscription options.
1130 @type options: L{dict}.
1131
1132 @param subscriptionIdentifier: Optional subscription identifier.
1133 @type subscriptionIdentifier: L{str}
1134 """
1135 request = self._request_class("optionsSet")
1136 request.recipient = service
1137 request.nodeIdentifier = nodeIdentifier
1138 request.subscriber = subscriber
1139 request.subscriptionIdentifier = subscriptionIdentifier
1140 request.sender = sender
1141
1142 form = data_form.Form(
1143 formType="submit", formNamespace=NS_PUBSUB_SUBSCRIBE_OPTIONS
1144 )
1145 form.makeFields(options)
1146 request.options = form
1147
1148 d = request.send(self.xmlstream)
1149 return d
1150
1151
1152 @implementer(IPubSubService, disco.IDisco)
1153 class PubSubService(XMPPHandler, IQHandlerMixin):
1154 """
1155 Protocol implementation for a XMPP Publish Subscribe Service.
1156
1157 The word Service here is used as taken from the Publish Subscribe
1158 specification. It is the party responsible for keeping nodes and their
1159 subscriptions, and sending out notifications.
1160
1161 Methods from the L{IPubSubService} interface that are called as a result
1162 of an XMPP request may raise exceptions. Alternatively the deferred
1163 returned by these methods may have their errback called. These are handled
1164 as follows:
1165
1166 - If the exception is an instance of L{error.StanzaError}, an error
1167 response iq is returned.
1168 - Any other exception is reported using L{log.msg}. An error response
1169 with the condition C{internal-server-error} is returned.
1170
1171 The default implementation of said methods raises an L{Unsupported}
1172 exception and are meant to be overridden.
1173
1174 @ivar discoIdentity: Service discovery identity as a dictionary with
1175 keys C{'category'}, C{'type'} and C{'name'}.
1176 @ivar pubSubFeatures: List of supported publish-subscribe features for
1177 service discovery, as L{str}.
1178 @type pubSubFeatures: L{list} or L{None}
1179 """
1180
1181 iqHandlers = {
1182 "/*": "_onPubSubRequest",
1183 }
1184
1185 _legacyHandlers = {
1186 "publish": ("publish", ["sender", "recipient", "nodeIdentifier", "items"]),
1187 "subscribe": (
1188 "subscribe",
1189 ["sender", "recipient", "nodeIdentifier", "subscriber"],
1190 ),
1191 "unsubscribe": (
1192 "unsubscribe",
1193 ["sender", "recipient", "nodeIdentifier", "subscriber"],
1194 ),
1195 "subscriptions": ("subscriptions", ["sender", "recipient"]),
1196 "affiliations": ("affiliations", ["sender", "recipient"]),
1197 "create": ("create", ["sender", "recipient", "nodeIdentifier"]),
1198 "getConfigurationOptions": ("getConfigurationOptions", []),
1199 "default": ("getDefaultConfiguration", ["sender", "recipient", "nodeType"]),
1200 "configureGet": ("getConfiguration", ["sender", "recipient", "nodeIdentifier"]),
1201 "configureSet": (
1202 "setConfiguration",
1203 ["sender", "recipient", "nodeIdentifier", "options"],
1204 ),
1205 "items": (
1206 "items",
1207 ["sender", "recipient", "nodeIdentifier", "maxItems", "itemIdentifiers"],
1208 ),
1209 "retract": (
1210 "retract",
1211 ["sender", "recipient", "nodeIdentifier", "itemIdentifiers"],
1212 ),
1213 "purge": ("purge", ["sender", "recipient", "nodeIdentifier"]),
1214 "delete": ("delete", ["sender", "recipient", "nodeIdentifier"]),
1215 }
1216
1217 _request_class = PubSubRequest
1218
1219 hideNodes = False
1220
1221 def __init__(self, resource=None):
1222 self.resource = resource
1223 self.discoIdentity = {
1224 "category": "pubsub",
1225 "type": "service",
1226 "name": "Generic Publish-Subscribe Service",
1227 }
1228
1229 self.pubSubFeatures = []
1230
1231 def connectionMade(self):
1232 self.xmlstream.addObserver(PUBSUB_REQUEST, self.handleRequest)
1233
1234 def getDiscoInfo(self, requestor, target, nodeIdentifier=""):
1235 def toInfo(nodeInfo):
1236 if not nodeInfo:
1237 return
1238
1239 nodeType, metaData = nodeInfo["type"], nodeInfo["meta-data"]
1240 info.append(disco.DiscoIdentity("pubsub", nodeType))
1241 if metaData:
1242 form = data_form.Form(
1243 formType="result", formNamespace=NS_PUBSUB_META_DATA
1244 )
1245 form.addField(
1246 data_form.Field(
1247 var="pubsub#node_type",
1248 value=nodeType,
1249 label="The type of node (collection or leaf)",
1250 )
1251 )
1252
1253 for metaDatum in metaData:
1254 form.addField(data_form.Field.fromDict(metaDatum))
1255
1256 info.append(form)
1257
1258 return
1259
1260 info = []
1261
1262 request = self._request_class("discoInfo")
1263
1264 if self.resource is not None:
1265 resource = self.resource.locateResource(request)
1266 identity = resource.discoIdentity
1267 features = resource.features
1268 getInfo = resource.getInfo
1269 else:
1270 category = self.discoIdentity["category"]
1271 idType = self.discoIdentity["type"]
1272 name = self.discoIdentity["name"]
1273 identity = disco.DiscoIdentity(category, idType, name)
1274 features = self.pubSubFeatures
1275 getInfo = self.getNodeInfo
1276
1277 if not nodeIdentifier:
1278 info.append(identity)
1279 info.append(disco.DiscoFeature(disco.NS_DISCO_ITEMS))
1280 info.extend(
1281 [
1282 disco.DiscoFeature("%s#%s" % (NS_PUBSUB, feature))
1283 for feature in features
1284 ]
1285 )
1286
1287 d = defer.maybeDeferred(getInfo, requestor, target, nodeIdentifier or "")
1288 d.addCallback(toInfo)
1289 d.addErrback(log.err)
1290 d.addCallback(lambda _: info)
1291 return d
1292
1293 def _parseNodes(self, nodes, target):
1294 """parse return values of resource.getNodes
1295
1296 basestring values are used as node
1297 tuple are unpacked as node, name
1298 """
1299 items = []
1300 for node in nodes:
1301 if not node:
1302 continue
1303 elif isinstance(node, str):
1304 items.append(disco.DiscoItem(target, node))
1305 else:
1306 _node, name = node
1307 items.append(disco.DiscoItem(target, _node, name))
1308 return items
1309
1310 def getDiscoItems(self, requestor, target, nodeIdentifier=""):
1311 if self.hideNodes:
1312 d = defer.succeed([])
1313 elif self.resource is not None:
1314 request = self._request_class("discoInfo")
1315 resource = self.resource.locateResource(request)
1316 d = resource.getNodes(requestor, target, nodeIdentifier)
1317 elif nodeIdentifier:
1318 d = defer.maybeDeferred(self.getNodes, requestor, target)
1319 else:
1320 d = defer.succeed([])
1321
1322 d.addCallback(self._parseNodes, target)
1323 return d
1324
1325 def _onPubSubRequest(self, iq):
1326 request = self._request_class.fromElement(iq)
1327
1328 if self.resource is not None:
1329 resource = self.resource.locateResource(request)
1330 else:
1331 resource = self
1332
1333 # Preprocess the request, knowing the handling resource
1334 try:
1335 preProcessor = getattr(self, "_preProcess_%s" % request.verb)
1336 except AttributeError:
1337 pass
1338 else:
1339 request = preProcessor(resource, request)
1340 if request is None:
1341 return defer.succeed(None)
1342
1343 # Process the request itself,
1344 if resource is not self:
1345 try:
1346 handler = getattr(resource, request.verb)
1347 except AttributeError:
1348 text = "Request verb: %s" % request.verb
1349 return defer.fail(Unsupported("", text))
1350
1351 d = handler(request)
1352 else:
1353 try:
1354 handlerName, argNames = self._legacyHandlers[request.verb]
1355 except KeyError:
1356 text = "Request verb: %s" % request.verb
1357 return defer.fail(Unsupported("", text))
1358
1359 handler = getattr(self, handlerName)
1360 args = [getattr(request, arg) for arg in argNames]
1361 d = handler(*args)
1362
1363 # If needed, translate the result into a response
1364 try:
1365 cb = getattr(self, "_toResponse_%s" % request.verb)
1366 except AttributeError:
1367 pass
1368 else:
1369 d.addCallback(cb, resource, request)
1370
1371 return d
1372
1373 def _toResponse_subscribe(
1374 self, result: Subscription, resource: "PubSubResource", request: PubSubRequest
1375 ) -> domish.Element:
1376 response = domish.Element((NS_PUBSUB, "pubsub"))
1377 response.addChild(result.toElement(NS_PUBSUB))
1378 return response
1379
1380 def _toResponse_unsubscribe(
1381 self,
1382 result: Subscription | None,
1383 resource: "PubSubResource",
1384 request: PubSubRequest,
1385 ) -> domish.Element:
1386 response = domish.Element((NS_PUBSUB, "pubsub"))
1387 if result is None:
1388 result = Subscription(request.nodeIdentifier, request.subscriber, "none")
1389 response.addChild(result.toElement(NS_PUBSUB))
1390 return response
1391
1392 def _toResponse_subscriptions(self, result, resource, request):
1393 response = domish.Element((NS_PUBSUB, "pubsub"))
1394 subscriptions = response.addElement("subscriptions")
1395 for subscription in result:
1396 subscriptions.addChild(subscription.toElement(NS_PUBSUB))
1397 return response
1398
1399 def _toResponse_affiliations(self, result, resource, request):
1400 response = domish.Element((NS_PUBSUB, "pubsub"))
1401 affiliations = response.addElement("affiliations")
1402
1403 for nodeIdentifier, affiliation in result:
1404 item = affiliations.addElement("affiliation")
1405 item["node"] = nodeIdentifier
1406 item["affiliation"] = affiliation
1407
1408 return response
1409
1410 def _toResponse_create(self, result, resource, request):
1411 if not request.nodeIdentifier or request.nodeIdentifier != result:
1412 response = domish.Element((NS_PUBSUB, "pubsub"))
1413 create = response.addElement("create")
1414 create["node"] = result
1415 return response
1416 else:
1417 return None
1418
1419 def _formFromConfiguration(self, resource, values):
1420 fieldDefs = resource.getConfigurationOptions()
1421 form = data_form.Form(formType="form", formNamespace=NS_PUBSUB_NODE_CONFIG)
1422 form.makeFields(values, fieldDefs)
1423 return form
1424
1425 def _checkConfiguration(self, resource, form):
1426 fieldDefs = resource.getConfigurationOptions()
1427 form.typeCheck(fieldDefs, filterUnknown=True)
1428
1429 def _preProcess_create(self, resource, request):
1430 if request.options:
1431 self._checkConfiguration(resource, request.options)
1432 return request
1433
1434 def _preProcess_default(self, resource, request):
1435 if request.nodeType not in ("leaf", "collection"):
1436 raise error.StanzaError("not-acceptable")
1437 else:
1438 return request
1439
1440 def _toResponse_default(self, options, resource, request):
1441 response = domish.Element((NS_PUBSUB_OWNER, "pubsub"))
1442 default = response.addElement("default")
1443 form = self._formFromConfiguration(resource, options)
1444 default.addChild(form.toElement())
1445 return response
1446
1447 def _toResponse_configureGet(self, options, resource, request):
1448 response = domish.Element((NS_PUBSUB_OWNER, "pubsub"))
1449 configure = response.addElement("configure")
1450 form = self._formFromConfiguration(resource, options)
1451 configure.addChild(form.toElement())
1452
1453 if request.nodeIdentifier:
1454 configure["node"] = request.nodeIdentifier
1455
1456 return response
1457
1458 def _preProcess_configureSet(self, resource, request):
1459 if request.options.formType == "cancel":
1460 return None
1461 else:
1462 self._checkConfiguration(resource, request.options)
1463 return request
1464
1465 def _toResponse_items(self, result, resource, request):
1466 response = domish.Element((NS_PUBSUB, "pubsub"))
1467 items = response.addElement("items")
1468 items["node"] = request.nodeIdentifier
1469
1470 for item in result:
1471 item.uri = NS_PUBSUB
1472 items.addChild(item)
1473
1474 return response
1475
1476 def _toResponse_subscriptionsGet(self, result, resource, request):
1477 response = domish.Element((NS_PUBSUB_OWNER, "pubsub"))
1478 subscriptions = response.addElement("subscriptions")
1479 subscriptions["node"] = request.nodeIdentifier
1480 for subscription in result:
1481 subscription_element = subscription.toElement(NS_PUBSUB)
1482 del subscription_element["node"]
1483 subscriptions.addChild(subscription_element)
1484 return response
1485
1486 def _createNotification(
1487 self, eventType, service, nodeIdentifier, subscriber, subscriptions=None
1488 ):
1489 headers = []
1490
1491 if subscriptions:
1492 for subscription in subscriptions:
1493 if nodeIdentifier != subscription.nodeIdentifier:
1494 headers.append(("Collection", subscription.nodeIdentifier))
1495
1496 message = domish.Element((None, "message"))
1497 message["from"] = service.full()
1498 message["to"] = subscriber.full()
1499 event = message.addElement((NS_PUBSUB_EVENT, "event"))
1500
1501 element = event.addElement(eventType)
1502 element["node"] = nodeIdentifier
1503
1504 if headers:
1505 message.addChild(shim.Headers(headers))
1506
1507 return message
1508
1509 def _toResponse_affiliationsGet(self, result, resource, request):
1510 response = domish.Element((NS_PUBSUB_OWNER, "pubsub"))
1511 affiliations = response.addElement("affiliations")
1512
1513 if request.nodeIdentifier:
1514 affiliations["node"] = request.nodeIdentifier
1515
1516 for entity, affiliation in result.items():
1517 item = affiliations.addElement("affiliation")
1518 item["jid"] = entity.full()
1519 item["affiliation"] = affiliation
1520
1521 return response
1522
1523 # public methods
1524
1525 def notifyPublish(self, service, nodeIdentifier, notifications):
1526 for subscriber, subscriptions, items in notifications:
1527 message = self._createNotification(
1528 "items", service, nodeIdentifier, subscriber, subscriptions
1529 )
1530 for item in items:
1531 item.uri = NS_PUBSUB_EVENT
1532 message.event.items.addChild(item)
1533 self.send(message)
1534
1535 def notifyRetract(self, service, nodeIdentifier, notifications):
1536 for subscriber, subscriptions, items in notifications:
1537 message = self._createNotification(
1538 "items", service, nodeIdentifier, subscriber, subscriptions
1539 )
1540 for item in items:
1541 retract = domish.Element((NS_PUBSUB_EVENT, "retract"))
1542 retract["id"] = item["id"]
1543 message.event.items.addChild(retract)
1544 self.send(message)
1545
1546 def notifyPurge(self, service, nodeIdentifier, subscribers):
1547 for subscriber in subscribers:
1548 message = self._createNotification(
1549 "purge", service, nodeIdentifier, subscriber
1550 )
1551 self.send(message)
1552
1553 def notifyDelete(self, service, nodeIdentifier, subscribers, redirectURI=None):
1554 for subscriber in subscribers:
1555 message = self._createNotification(
1556 "delete", service, nodeIdentifier, subscriber
1557 )
1558 if redirectURI:
1559 redirect = message.event.delete.addElement("redirect")
1560 redirect["uri"] = redirectURI
1561 self.send(message)
1562
1563 def getNodeInfo(self, requestor, service, nodeIdentifier):
1564 return None
1565
1566 def getNodes(self, requestor, service):
1567 return []
1568
1569 def publish(self, requestor, service, nodeIdentifier, items, options=None):
1570 raise Unsupported("publish")
1571
1572 def subscribe(self, requestor, service, nodeIdentifier, subscriber):
1573 raise Unsupported("subscribe")
1574
1575 def unsubscribe(self, requestor, service, nodeIdentifier, subscriber):
1576 raise Unsupported("subscribe")
1577
1578 def subscriptions(self, requestor, service):
1579 raise Unsupported("retrieve-subscriptions")
1580
1581 def affiliations(self, requestor, service):
1582 raise Unsupported("retrieve-affiliations")
1583
1584 def create(self, requestor, service, nodeIdentifier):
1585 raise Unsupported("create-nodes")
1586
1587 def getConfigurationOptions(self):
1588 return {}
1589
1590 def getDefaultConfiguration(self, requestor, service, nodeType):
1591 raise Unsupported("retrieve-default")
1592
1593 def getConfiguration(self, requestor, service, nodeIdentifier):
1594 raise Unsupported("config-node")
1595
1596 def setConfiguration(self, requestor, service, nodeIdentifier, options):
1597 raise Unsupported("config-node")
1598
1599 def items(self, requestor, service, nodeIdentifier, maxItems, itemIdentifiers):
1600 raise Unsupported("retrieve-items")
1601
1602 def retract(self, requestor, service, nodeIdentifier, itemIdentifiers):
1603 raise Unsupported("retract-items")
1604
1605 def purge(self, requestor, service, nodeIdentifier):
1606 raise Unsupported("purge-nodes")
1607
1608 def delete(self, requestor, service, nodeIdentifier):
1609 raise Unsupported("delete-nodes")
1610
1611
1612 @implementer(IPubSubResource)
1613 class PubSubResource:
1614 """
1615 Base resource for publish-subscribe nodes.
1616
1617 This class provides a base implementation for pubsub resources that handle specific
1618 nodes or collections of nodes. Subclasses should override the methods they wish to
1619 support.
1620
1621 The resource is used by L{PubSubService} to delegate pubsub requests to appropriate
1622 handlers based on the node identifier in the request.
1623 """
1624
1625 features: list[str] = []
1626 discoIdentity = disco.DiscoIdentity("pubsub", "service", "Publish-Subscribe Service")
1627
1628 def locateResource(self, request: PubSubRequest) -> Self:
1629 """
1630 Locate the resource that should handle the given request.
1631
1632 This method is called by L{PubSubService} to determine which resource should
1633 handle a pubsub request. By default, it returns itself, but subclasses can
1634 override this to delegate to different resources based on the request (e.g., based
1635 on the node identifier).
1636
1637 @param request: The publish-subscribe request to handle.
1638
1639 @return: The resource that should handle the request.
1640 """
1641 return self
1642
1643 def getInfo(
1644 self,
1645 requestor: jid.JID,
1646 service: jid.JID,
1647 nodeIdentifier: str,
1648 ) -> defer.Deferred[None | dict[str, object]]:
1649 """
1650 Get node type and meta-data for service discovery.
1651
1652 This method is called when a disco#info request is made for a node.
1653 The returned dictionary should contain information about the node type and its
1654 meta-data.
1655
1656 @param requestor: The entity that made the request.
1657 @param service: The pubsub service entity.
1658 @param nodeIdentifier: The identifier of the node to get info for.
1659
1660 @return: A deferred that fires with a dictionary containing node info.
1661 The dictionary should have keys 'type' (str: 'leaf' or 'collection') and
1662 'meta-data' (list of meta-data dicts). Return None or empty dict if no
1663 info is available.
1664 """
1665 return defer.succeed(None)
1666
1667 def getNodes(
1668 self,
1669 requestor: jid.JID,
1670 service: jid.JID,
1671 nodeIdentifier: str,
1672 ) -> defer.Deferred[list[str | tuple[str, str]]]:
1673 """
1674 Get child nodes contained by this node.
1675
1676 This method is called when a disco#items request is made for a node. It should
1677 return a list of child node identifiers.
1678
1679 @param requestor: The entity that made the request.
1680 @param service: The pubsub service entity.
1681 @param nodeIdentifier: The identifier of the parent node.
1682
1683 @return: A deferred that fires with a list of child node identifiers.
1684 Each element can be either a string (node identifier only) or a tuple of
1685 (node_identifier, node_name).
1686 """
1687 return defer.succeed([])
1688
1689 def getConfigurationOptions(self) -> dict[str, dict[str, object]]:
1690 """
1691 Retrieve all known node configuration options.
1692
1693 This method returns the schema for node configuration options that can be set when
1694 creating or configuring a node. The returned dictionary maps option names to their
1695 definitions.
1696
1697 Each option definition is a dictionary with the following keys:
1698 - 'type' (str): The field type (e.g., 'boolean', 'text-single', 'list-single',
1699 'jid-single', etc.)
1700 - 'label' (str): A human-readable label for the option
1701 - 'options' (dict, optional): For list types, a mapping of valid values to their
1702 labels
1703 - 'default' (any, optional): The default value for this option
1704 - 'required' (bool, optional): Whether this option is required
1705
1706 Example::
1707
1708 {
1709 "pubsub#persist_items": {
1710 "type": "boolean",
1711 "label": "Persist items to storage"
1712 },
1713 "pubsub#max_items": {
1714 "type": "text-single",
1715 "label": "Maximum number of items to store"
1716 },
1717 "pubsub#send_last_published_item": {
1718 "type": "list-single",
1719 "label": "When to send the last published item",
1720 "options": {
1721 "never": "Never",
1722 "on_sub": "On subscription"
1723 }
1724 }
1725 }
1726
1727 @return: A dictionary of configuration option definitions.
1728 """
1729 return {}
1730
1731 def publish(self, request: PubSubRequest) -> defer.Deferred[None | domish.Element]:
1732 """
1733 Handle a publish request.
1734
1735 This method is called when a client publishes items to a node. The implementation
1736 should store the items and notify subscribers.
1737
1738 @param request: The publish request containing node identifier, items to publish,
1739 and optional publish-options.
1740
1741 @return: A deferred that fires with:
1742 - C{None} if the publish operation should return an empty IQ result
1743 - A C{domish.Element} containing a C{<publish>} element with the published
1744 item(s). The element should have the form::
1745
1746 <pubsub xmlns="http://jabber.org/protocol/pubsub">
1747 <publish node="node_identifier">
1748 <item id="item_id"/>
1749 </publish>
1750 </pubsub>
1751
1752 @raises Unsupported: If publish is not supported (default behavior).
1753 """
1754 return defer.fail(Unsupported("publish"))
1755
1756 def subscribe(self, request: PubSubRequest) -> defer.Deferred[Subscription]:
1757 """
1758 Handle a subscribe request.
1759
1760 This method is called when a client wants to subscribe to a node. The
1761 implementation should create or update the subscription and return the resulting
1762 subscription state.
1763
1764 @param request: The subscribe request containing node identifier, subscriber JID,
1765 and optional subscription options.
1766
1767 @return: A deferred that fires with a L{Subscription} object representing the
1768 resulting subscription state.
1769
1770 @raises Unsupported: If subscribe is not supported (default behavior).
1771 """
1772 return defer.fail(Unsupported("subscribe"))
1773
1774 def unsubscribe(self, request: PubSubRequest) -> defer.Deferred[None]:
1775 """
1776 Handle an unsubscribe request.
1777
1778 This method is called when a client wants to unsubscribe from a node.
1779 The implementation should remove the subscription.
1780
1781 @param request: The unsubscribe request containing node identifier and subscriber
1782 JID.
1783
1784 @return: A deferred that fires when the unsubscribe operation completes.
1785
1786 @raises Unsupported: If unsubscribe is not supported (default behavior).
1787 """
1788 return defer.fail(Unsupported("subscribe"))
1789
1790 def subscriptions(self, request: PubSubRequest) -> defer.Deferred[list[Subscription]]:
1791 """
1792 Handle a subscriptions retrieval request.
1793
1794 This method is called when a client wants to retrieve their subscriptions. The
1795 implementation should return all subscriptions for the requesting entity.
1796
1797 @param request: The subscriptions request containing optional node identifier
1798 filter.
1799
1800 @return: A deferred that fires with a list of L{Subscription} objects.
1801
1802 @raises Unsupported: If subscriptions retrieval is not supported (default
1803 behavior).
1804 """
1805 return defer.fail(Unsupported("retrieve-subscriptions"))
1806
1807 def affiliations(
1808 self, request: PubSubRequest
1809 ) -> defer.Deferred[list[tuple[str, str]]]:
1810 """
1811 Handle an affiliations retrieval request.
1812
1813 This method is called when a client wants to retrieve affiliations for entities.
1814 The implementation should return affiliations as (node_identifier,
1815 affiliation_state) tuples.
1816
1817 Valid affiliation states are: 'owner', 'admin', 'publisher', 'subscribed', 'none',
1818 'outcast'.
1819
1820 @param request: The affiliations request containing optional node identifier
1821 filter.
1822
1823 @return: A deferred that fires with a list of (node_identifier, affiliation_state)
1824 tuples.
1825
1826 @raises Unsupported: If affiliations retrieval is not supported (default
1827 behavior).
1828 """
1829 return defer.fail(Unsupported("retrieve-affiliations"))
1830
1831 def create(self, request: PubSubRequest) -> defer.Deferred[str]:
1832 """
1833 Handle a node creation request.
1834
1835 This method is called when a client wants to create a new node. The implementation
1836 should create the node with the specified configuration and return the node
1837 identifier.
1838
1839 @param request: The create request containing optional suggested node identifier
1840 and configuration options.
1841
1842 @return: A deferred that fires with the identifier of the created node. This may
1843 differ from the suggested identifier if the service assigns its own
1844 identifier.
1845
1846 @raises Unsupported: If node creation is not supported (default behavior).
1847 """
1848 return defer.fail(Unsupported("create-nodes"))
1849
1850 def default(self, request: PubSubRequest) -> defer.Deferred[dict[str, object]]:
1851 """
1852 Handle a default node configuration request.
1853
1854 This method is called when a client requests the default configuration for a new
1855 node of a specific type.
1856
1857 @param request: The default request containing the node type ('leaf' or
1858 'collection').
1859
1860 @return: A deferred that fires with a dictionary representing the default
1861 configuration. Keys are field names, values are the default values (str, int,
1862 or bool).
1863
1864 @raises Unsupported: If default configuration retrieval is not supported (default
1865 behavior).
1866 """
1867 return defer.fail(Unsupported("retrieve-default"))
1868
1869 def configureGet(self, request: PubSubRequest) -> defer.Deferred[dict[str, object]]:
1870 """
1871 Handle a node configuration retrieval request.
1872
1873 This method is called when a client requests the current configuration of an
1874 existing node.
1875
1876 @param request: The configure request containing the node identifier.
1877
1878 @return: A deferred that fires with a dictionary representing the node
1879 configuration. Keys are field names, values are the current values (str, int,
1880 or bool).
1881
1882 @raises Unsupported: If configuration retrieval is not supported (default
1883 behavior).
1884 """
1885 return defer.fail(Unsupported("config-node"))
1886
1887 def configureSet(self, request: PubSubRequest) -> defer.Deferred[None]:
1888 """
1889 Handle a node configuration update request.
1890
1891 This method is called when a client wants to update the configuration of an
1892 existing node.
1893
1894 @param request: The configure request containing the node identifier and new
1895 configuration options in request.options.
1896
1897 @return: A deferred that fires when the configuration update completes.
1898
1899 @raises Unsupported: If configuration update is not supported (default behavior).
1900 """
1901 return defer.fail(Unsupported("config-node"))
1902
1903 def items(
1904 self, request: PubSubRequest
1905 ) -> defer.Deferred[
1906 list[domish.Element] | tuple[list[domish.Element], "rsm.RSMResponse"]
1907 ]:
1908 """
1909 Handle an items retrieval request.
1910
1911 This method is called when a client wants to retrieve published items from a node.
1912
1913 @param request: The items request containing the node identifier, optional
1914 max_items limit, optional item identifiers to retrieve, and optional
1915 subscription identifier.
1916
1917 @return: A deferred that fires with:
1918 - A list of item elements (L{domish.Element}) for basic implementations.
1919 - A tuple of (list of item elements, L{rsm.RSMResponse}) when using RSM
1920 (Result Set Management) support via L{rsm.PubSubService}.
1921
1922 @raises Unsupported: If items retrieval is not supported (default behavior).
1923 """
1924 return defer.fail(Unsupported("retrieve-items"))
1925
1926 def retract(self, request: PubSubRequest) -> defer.Deferred[None]:
1927 """
1928 Handle an items retraction request.
1929
1930 This method is called when a client wants to retract previously published items
1931 from a node.
1932
1933 @param request: The retract request containing the node identifier, item
1934 identifiers to retract, and optional notify flag.
1935
1936 @return: A deferred that fires when the retraction operation completes.
1937
1938 @raises Unsupported: If items retraction is not supported (default behavior).
1939 """
1940 return defer.fail(Unsupported("retract-items"))
1941
1942 def purge(self, request: PubSubRequest) -> defer.Deferred[None]:
1943 """
1944 Handle a node purge request.
1945
1946 This method is called when a client wants to purge all items from a node.
1947
1948 @param request: The purge request containing the node identifier.
1949
1950 @return: A deferred that fires when the purge operation completes.
1951
1952 @raises Unsupported: If node purging is not supported (default behavior).
1953 """
1954 return defer.fail(Unsupported("purge-nodes"))
1955
1956 def delete(self, request: PubSubRequest) -> defer.Deferred[None]:
1957 """
1958 Handle a node deletion request.
1959
1960 This method is called when a client wants to delete a node. The implementation
1961 should remove the node and all its data.
1962
1963 @param request: The delete request containing the node identifier.
1964
1965 @return: A deferred that fires when the deletion operation completes.
1966
1967 @raises Unsupported: If node deletion is not supported (default behavior).
1968 """
1969 return defer.fail(Unsupported("delete-nodes"))
1970
1971 def affiliationsGet(
1972 self, request: PubSubRequest
1973 ) -> defer.Deferred[dict[jid.JID, str]]:
1974 """
1975 Handle an affiliations retrieval request (owner interface).
1976
1977 This method is called when an owner/admin wants to retrieve affiliations for a
1978 specific node.
1979
1980 @param request: The affiliations request containing the node identifier.
1981
1982 @return: A deferred that fires with a dictionary mapping entity JIDs to their
1983 affiliation states. Valid states are: 'owner', 'admin', 'publisher',
1984 'subscribed', 'none', 'outcast'.
1985
1986 @raises Unsupported: If affiliations retrieval is not supported (default
1987 behavior).
1988 """
1989 return defer.fail(Unsupported("modify-affiliations"))
1990
1991 def affiliationsSet(self, request: PubSubRequest) -> defer.Deferred[None]:
1992 """
1993 Handle an affiliations update request (owner interface).
1994
1995 This method is called when an owner/admin wants to update affiliations for
1996 entities in a node.
1997
1998 @param request: The affiliations request containing the node identifier and the
1999 affiliations to set in request.affiliations (dict mapping JID to affiliation).
2000
2001 @return: A deferred that fires when the affiliations update completes.
2002
2003 @raises Unsupported: If affiliations update is not supported (default behavior).
2004 """
2005 return defer.fail(Unsupported("modify-affiliations"))
2006
2007 def subscriptionsGet(
2008 self, request: PubSubRequest
2009 ) -> defer.Deferred[list[Subscription]]:
2010 """
2011 Handle a subscriptions retrieval request (owner interface).
2012
2013 This method is called when an owner/admin wants to retrieve all subscriptions for
2014 a specific node.
2015
2016 @param request: The subscriptions request containing the node identifier.
2017
2018 @return: A deferred that fires with a list of L{Subscription} objects representing
2019 all subscriptions for the node.
2020
2021 @raises Unsupported: If subscriptions management is not supported (default
2022 behavior).
2023 """
2024 return defer.fail(Unsupported("manage-subscriptions"))
2025
2026 def subscriptionsSet(self, request: PubSubRequest) -> defer.Deferred[None]:
2027 """
2028 Handle a subscriptions update request (owner interface).
2029
2030 This method is called when an owner/admin wants to update subscriptions for
2031 entities in a node.
2032
2033 @param request: The subscriptions request containing the node identifier and the
2034 subscriptions to set in request.subscriptions (set of Subscription objects).
2035
2036 @return: A deferred that fires when the subscriptions update completes.
2037
2038 @raises Unsupported: If subscriptions management is not supported (default
2039 behavior).
2040 """
2041 return defer.fail(Unsupported("manage-subscriptions"))