| 1 |
# -*- test-case-name: tx_xmpp.test.test.test_xmppim -*- |
| 2 |
# |
| 3 |
# Copyright (c) Ralph Meijer. |
| 4 |
# See LICENSE for details. |
| 5 |
|
| 6 |
""" |
| 7 |
XMPP IM protocol support. |
| 8 |
|
| 9 |
This module provides generic implementations for the protocols defined in |
| 10 |
U{RFC 6121<http://www.xmpp.org/rfcs/rfc6121.html>} (XMPP IM). |
| 11 |
""" |
| 12 |
|
| 13 |
from twisted.internet import defer |
| 14 |
from twisted.words.protocols.jabber import error |
| 15 |
from twisted.words.protocols.jabber.jid import JID |
| 16 |
from twisted.words.xish import domish |
| 17 |
|
| 18 |
from .constants import NS_XML |
| 19 |
from .generic import ErrorStanza, Stanza, Request |
| 20 |
from .subprotocols import IQHandlerMixin, XMPPHandler |
| 21 |
|
| 22 |
NS_ROSTER = "jabber:iq:roster" |
| 23 |
|
| 24 |
XPATH_ROSTER_SET = "/iq[@type='set']/query[@xmlns='%s']" % NS_ROSTER |
| 25 |
|
| 26 |
|
| 27 |
class Presence(domish.Element): |
| 28 |
def __init__(self, to=None, type=None): |
| 29 |
domish.Element.__init__(self, (None, "presence")) |
| 30 |
if type: |
| 31 |
self["type"] = type |
| 32 |
|
| 33 |
if to is not None: |
| 34 |
self["to"] = to.full() |
| 35 |
|
| 36 |
|
| 37 |
class AvailablePresence(Presence): |
| 38 |
def __init__(self, to=None, show=None, statuses=None, priority=0): |
| 39 |
Presence.__init__(self, to, type=None) |
| 40 |
|
| 41 |
if show in ["away", "xa", "chat", "dnd"]: |
| 42 |
self.addElement("show", content=show) |
| 43 |
|
| 44 |
if statuses is not None: |
| 45 |
for lang, status in statuses.items(): |
| 46 |
s = self.addElement("status", content=status) |
| 47 |
if lang: |
| 48 |
s[(NS_XML, "lang")] = lang |
| 49 |
|
| 50 |
if priority != 0: |
| 51 |
self.addElement("priority", content=str(int(priority))) |
| 52 |
|
| 53 |
|
| 54 |
class UnavailablePresence(Presence): |
| 55 |
def __init__(self, to=None, statuses=None): |
| 56 |
Presence.__init__(self, to, type="unavailable") |
| 57 |
|
| 58 |
if statuses is not None: |
| 59 |
for lang, status in statuses.items(): |
| 60 |
s = self.addElement("status", content=status) |
| 61 |
if lang: |
| 62 |
s[(NS_XML, "lang")] = lang |
| 63 |
|
| 64 |
|
| 65 |
class PresenceClientProtocol(XMPPHandler): |
| 66 |
|
| 67 |
def connectionInitialized(self): |
| 68 |
self.xmlstream.addObserver("/presence", self._onPresence) |
| 69 |
|
| 70 |
def _getStatuses(self, presence): |
| 71 |
statuses = {} |
| 72 |
for element in presence.elements(): |
| 73 |
if element.name == "status": |
| 74 |
lang = element.getAttribute((NS_XML, "lang")) |
| 75 |
text = str(element) |
| 76 |
statuses[lang] = text |
| 77 |
return statuses |
| 78 |
|
| 79 |
def _onPresence(self, presence): |
| 80 |
type = presence.getAttribute("type", "available") |
| 81 |
try: |
| 82 |
handler = getattr(self, "_onPresence%s" % (type.capitalize())) |
| 83 |
except AttributeError: |
| 84 |
return |
| 85 |
else: |
| 86 |
handler(presence) |
| 87 |
|
| 88 |
def _onPresenceAvailable(self, presence): |
| 89 |
entity = JID(presence["from"]) |
| 90 |
|
| 91 |
show = str(presence.show or "") |
| 92 |
if show not in ["away", "xa", "chat", "dnd"]: |
| 93 |
show = None |
| 94 |
|
| 95 |
statuses = self._getStatuses(presence) |
| 96 |
|
| 97 |
try: |
| 98 |
priority = int(str(presence.priority or "")) or 0 |
| 99 |
except ValueError: |
| 100 |
priority = 0 |
| 101 |
|
| 102 |
self.availableReceived(entity, show, statuses, priority) |
| 103 |
|
| 104 |
def _onPresenceUnavailable(self, presence): |
| 105 |
entity = JID(presence["from"]) |
| 106 |
|
| 107 |
statuses = self._getStatuses(presence) |
| 108 |
|
| 109 |
self.unavailableReceived(entity, statuses) |
| 110 |
|
| 111 |
def _onPresenceSubscribed(self, presence): |
| 112 |
self.subscribedReceived(JID(presence["from"])) |
| 113 |
|
| 114 |
def _onPresenceUnsubscribed(self, presence): |
| 115 |
self.unsubscribedReceived(JID(presence["from"])) |
| 116 |
|
| 117 |
def _onPresenceSubscribe(self, presence): |
| 118 |
self.subscribeReceived(JID(presence["from"])) |
| 119 |
|
| 120 |
def _onPresenceUnsubscribe(self, presence): |
| 121 |
self.unsubscribeReceived(JID(presence["from"])) |
| 122 |
|
| 123 |
def availableReceived(self, entity, show=None, statuses=None, priority=0): |
| 124 |
""" |
| 125 |
Available presence was received. |
| 126 |
|
| 127 |
@param entity: entity from which the presence was received. |
| 128 |
@type entity: {JID} |
| 129 |
@param show: detailed presence information. One of C{'away'}, C{'xa'}, |
| 130 |
C{'chat'}, C{'dnd'} or C{None}. |
| 131 |
@type show: L{str} or C{NoneType} |
| 132 |
@param statuses: dictionary of natural language descriptions of the |
| 133 |
availability status, keyed by the language |
| 134 |
descriptor. A status without a language |
| 135 |
specified, is keyed with C{None}. |
| 136 |
@type statuses: L{dict} |
| 137 |
@param priority: priority level of the resource. |
| 138 |
@type priority: L{int} |
| 139 |
""" |
| 140 |
|
| 141 |
def unavailableReceived(self, entity, statuses=None): |
| 142 |
""" |
| 143 |
Unavailable presence was received. |
| 144 |
|
| 145 |
@param entity: entity from which the presence was received. |
| 146 |
@type entity: {JID} |
| 147 |
@param statuses: dictionary of natural language descriptions of the |
| 148 |
availability status, keyed by the language |
| 149 |
descriptor. A status without a language |
| 150 |
specified, is keyed with C{None}. |
| 151 |
@type statuses: L{dict} |
| 152 |
""" |
| 153 |
|
| 154 |
def subscribedReceived(self, entity): |
| 155 |
""" |
| 156 |
Subscription approval confirmation was received. |
| 157 |
|
| 158 |
@param entity: entity from which the confirmation was received. |
| 159 |
@type entity: {JID} |
| 160 |
""" |
| 161 |
|
| 162 |
def unsubscribedReceived(self, entity): |
| 163 |
""" |
| 164 |
Unsubscription confirmation was received. |
| 165 |
|
| 166 |
@param entity: entity from which the confirmation was received. |
| 167 |
@type entity: {JID} |
| 168 |
""" |
| 169 |
|
| 170 |
def subscribeReceived(self, entity): |
| 171 |
""" |
| 172 |
Subscription request was received. |
| 173 |
|
| 174 |
@param entity: entity from which the request was received. |
| 175 |
@type entity: {JID} |
| 176 |
""" |
| 177 |
|
| 178 |
def unsubscribeReceived(self, entity): |
| 179 |
""" |
| 180 |
Unsubscription request was received. |
| 181 |
|
| 182 |
@param entity: entity from which the request was received. |
| 183 |
@type entity: {JID} |
| 184 |
""" |
| 185 |
|
| 186 |
def available(self, entity=None, show=None, statuses=None, priority=0): |
| 187 |
""" |
| 188 |
Send available presence. |
| 189 |
|
| 190 |
@param entity: optional entity to which the presence should be sent. |
| 191 |
@type entity: {JID} |
| 192 |
@param show: optional detailed presence information. One of C{'away'}, |
| 193 |
C{'xa'}, C{'chat'}, C{'dnd'}. |
| 194 |
@type show: L{str} |
| 195 |
@param statuses: dictionary of natural language descriptions of the |
| 196 |
availability status, keyed by the language |
| 197 |
descriptor. A status without a language |
| 198 |
specified, is keyed with C{None}. |
| 199 |
@type statuses: L{dict} |
| 200 |
@param priority: priority level of the resource. |
| 201 |
@type priority: L{int} |
| 202 |
""" |
| 203 |
self.send(AvailablePresence(entity, show, statuses, priority)) |
| 204 |
|
| 205 |
def unavailable(self, entity=None, statuses=None): |
| 206 |
""" |
| 207 |
Send unavailable presence. |
| 208 |
|
| 209 |
@param entity: optional entity to which the presence should be sent. |
| 210 |
@type entity: {JID} |
| 211 |
@param statuses: dictionary of natural language descriptions of the |
| 212 |
availability status, keyed by the language |
| 213 |
descriptor. A status without a language |
| 214 |
specified, is keyed with C{None}. |
| 215 |
@type statuses: L{dict} |
| 216 |
""" |
| 217 |
self.send(UnavailablePresence(entity, statuses)) |
| 218 |
|
| 219 |
def subscribe(self, entity): |
| 220 |
""" |
| 221 |
Send subscription request |
| 222 |
|
| 223 |
@param entity: entity to subscribe to. |
| 224 |
@type entity: {JID} |
| 225 |
""" |
| 226 |
self.send(Presence(to=entity, type="subscribe")) |
| 227 |
|
| 228 |
def unsubscribe(self, entity): |
| 229 |
""" |
| 230 |
Send unsubscription request |
| 231 |
|
| 232 |
@param entity: entity to unsubscribe from. |
| 233 |
@type entity: {JID} |
| 234 |
""" |
| 235 |
self.send(Presence(to=entity, type="unsubscribe")) |
| 236 |
|
| 237 |
def subscribed(self, entity): |
| 238 |
""" |
| 239 |
Send subscription confirmation. |
| 240 |
|
| 241 |
@param entity: entity that subscribed. |
| 242 |
@type entity: {JID} |
| 243 |
""" |
| 244 |
self.send(Presence(to=entity, type="subscribed")) |
| 245 |
|
| 246 |
def unsubscribed(self, entity): |
| 247 |
""" |
| 248 |
Send unsubscription confirmation. |
| 249 |
|
| 250 |
@param entity: entity that unsubscribed. |
| 251 |
@type entity: {JID} |
| 252 |
""" |
| 253 |
self.send(Presence(to=entity, type="unsubscribed")) |
| 254 |
|
| 255 |
|
| 256 |
class BasePresence(Stanza): |
| 257 |
""" |
| 258 |
Stanza of kind presence. |
| 259 |
""" |
| 260 |
|
| 261 |
stanzaKind = "presence" |
| 262 |
|
| 263 |
|
| 264 |
class AvailabilityPresence(BasePresence): |
| 265 |
""" |
| 266 |
Presence. |
| 267 |
|
| 268 |
This represents availability presence (as opposed to |
| 269 |
L{SubscriptionPresence}). |
| 270 |
|
| 271 |
@ivar available: The availability being communicated. |
| 272 |
@type available: L{bool} |
| 273 |
@ivar show: More specific availability. Can be one of C{'chat'}, C{'away'}, |
| 274 |
C{'xa'}, C{'dnd'} or C{None}. |
| 275 |
@type show: L{str} or C{NoneType} |
| 276 |
@ivar statuses: Natural language texts to detail the (un)availability. |
| 277 |
These are represented as a mapping from language code |
| 278 |
(L{str} or C{None}) to the corresponding text (L{str}). |
| 279 |
If the key is C{None}, the associated text is in the |
| 280 |
default language. |
| 281 |
@type statuses: L{dict} |
| 282 |
@ivar priority: Priority level for this resource. Must be between -128 and |
| 283 |
127. Defaults to 0. |
| 284 |
@type priority: L{int} |
| 285 |
""" |
| 286 |
|
| 287 |
childParsers = { |
| 288 |
(None, "show"): "_childParser_show", |
| 289 |
(None, "status"): "_childParser_status", |
| 290 |
(None, "priority"): "_childParser_priority", |
| 291 |
} |
| 292 |
|
| 293 |
def __init__( |
| 294 |
self, |
| 295 |
recipient=None, |
| 296 |
sender=None, |
| 297 |
available=True, |
| 298 |
show=None, |
| 299 |
status=None, |
| 300 |
statuses=None, |
| 301 |
priority=0, |
| 302 |
): |
| 303 |
BasePresence.__init__(self, recipient=recipient, sender=sender) |
| 304 |
self.available = available |
| 305 |
self.show = show |
| 306 |
self.statuses = statuses or {} |
| 307 |
if status: |
| 308 |
self.statuses[None] = status |
| 309 |
self.priority = priority |
| 310 |
|
| 311 |
def __get_status(self): |
| 312 |
if None in self.statuses: |
| 313 |
return self.statuses[None] |
| 314 |
elif self.statuses: |
| 315 |
for status in self.status.values(): |
| 316 |
return status |
| 317 |
else: |
| 318 |
return None |
| 319 |
|
| 320 |
status = property(__get_status) |
| 321 |
|
| 322 |
def _childParser_show(self, element): |
| 323 |
show = str(element) |
| 324 |
if show in ("chat", "away", "xa", "dnd"): |
| 325 |
self.show = show |
| 326 |
|
| 327 |
def _childParser_status(self, element): |
| 328 |
lang = element.getAttribute((NS_XML, "lang"), None) |
| 329 |
text = str(element) |
| 330 |
self.statuses[lang] = text |
| 331 |
|
| 332 |
def _childParser_priority(self, element): |
| 333 |
try: |
| 334 |
self.priority = int(str(element)) |
| 335 |
except ValueError: |
| 336 |
pass |
| 337 |
|
| 338 |
def parseElement(self, element): |
| 339 |
BasePresence.parseElement(self, element) |
| 340 |
|
| 341 |
if self.stanzaType == "unavailable": |
| 342 |
self.available = False |
| 343 |
|
| 344 |
def toElement(self): |
| 345 |
if not self.available: |
| 346 |
self.stanzaType = "unavailable" |
| 347 |
|
| 348 |
presence = BasePresence.toElement(self) |
| 349 |
|
| 350 |
if self.available: |
| 351 |
if self.show in ("chat", "away", "xa", "dnd"): |
| 352 |
presence.addElement("show", content=self.show) |
| 353 |
if self.priority != 0: |
| 354 |
presence.addElement("priority", content=str(self.priority)) |
| 355 |
|
| 356 |
for lang, text in self.statuses.items(): |
| 357 |
status = presence.addElement("status", content=text) |
| 358 |
if lang: |
| 359 |
status[(NS_XML, "lang")] = lang |
| 360 |
|
| 361 |
return presence |
| 362 |
|
| 363 |
|
| 364 |
class SubscriptionPresence(BasePresence): |
| 365 |
""" |
| 366 |
Presence subscription request or response. |
| 367 |
|
| 368 |
This kind of presence is used to represent requests for presence |
| 369 |
subscription and their replies. |
| 370 |
|
| 371 |
Based on L{BasePresence} and {Stanza}, it just uses the C{stanzaType} |
| 372 |
attribute to represent the type of subscription presence. This can be |
| 373 |
one of C{'subscribe'}, C{'unsubscribe'}, C{'subscribed'} and |
| 374 |
C{'unsubscribed'}. |
| 375 |
""" |
| 376 |
|
| 377 |
|
| 378 |
class ProbePresence(BasePresence): |
| 379 |
""" |
| 380 |
Presence probe request. |
| 381 |
""" |
| 382 |
|
| 383 |
stanzaType = "probe" |
| 384 |
|
| 385 |
|
| 386 |
class BasePresenceProtocol(XMPPHandler): |
| 387 |
""" |
| 388 |
XMPP Presence base protocol handler. |
| 389 |
|
| 390 |
This class is the base for protocol handlers that receive presence |
| 391 |
stanzas. Listening to all incoming presence stanzas, it extracts the |
| 392 |
stanza's type and looks up a matching stanza parser and calls the |
| 393 |
associated method. The method's name is the type + C{Received}. E.g. |
| 394 |
C{availableReceived}. See L{PresenceProtocol} for a complete example. |
| 395 |
|
| 396 |
@cvar presenceTypeParserMap: Maps presence stanza types to their respective |
| 397 |
stanza parser classes (derived from L{Stanza}). |
| 398 |
@type presenceTypeParserMap: L{dict} |
| 399 |
""" |
| 400 |
|
| 401 |
presenceTypeParserMap = {} |
| 402 |
|
| 403 |
def connectionInitialized(self): |
| 404 |
self.xmlstream.addObserver("/presence", self._onPresence) |
| 405 |
|
| 406 |
def _onPresence(self, element): |
| 407 |
""" |
| 408 |
Called when a presence stanza has been received. |
| 409 |
""" |
| 410 |
stanza = Stanza.fromElement(element) |
| 411 |
|
| 412 |
presenceType = stanza.stanzaType or "available" |
| 413 |
|
| 414 |
try: |
| 415 |
parser = self.presenceTypeParserMap[presenceType] |
| 416 |
except KeyError: |
| 417 |
return |
| 418 |
|
| 419 |
presence = parser.fromElement(element) |
| 420 |
|
| 421 |
try: |
| 422 |
handler = getattr(self, "%sReceived" % presenceType) |
| 423 |
except AttributeError: |
| 424 |
return |
| 425 |
else: |
| 426 |
handler(presence) |
| 427 |
|
| 428 |
|
| 429 |
class PresenceProtocol(BasePresenceProtocol): |
| 430 |
|
| 431 |
presenceTypeParserMap = { |
| 432 |
"error": ErrorStanza, |
| 433 |
"available": AvailabilityPresence, |
| 434 |
"unavailable": AvailabilityPresence, |
| 435 |
"subscribe": SubscriptionPresence, |
| 436 |
"unsubscribe": SubscriptionPresence, |
| 437 |
"subscribed": SubscriptionPresence, |
| 438 |
"unsubscribed": SubscriptionPresence, |
| 439 |
"probe": ProbePresence, |
| 440 |
} |
| 441 |
|
| 442 |
def errorReceived(self, presence): |
| 443 |
""" |
| 444 |
Error presence was received. |
| 445 |
""" |
| 446 |
pass |
| 447 |
|
| 448 |
def availableReceived(self, presence): |
| 449 |
""" |
| 450 |
Available presence was received. |
| 451 |
""" |
| 452 |
pass |
| 453 |
|
| 454 |
def unavailableReceived(self, presence): |
| 455 |
""" |
| 456 |
Unavailable presence was received. |
| 457 |
""" |
| 458 |
pass |
| 459 |
|
| 460 |
def subscribedReceived(self, presence): |
| 461 |
""" |
| 462 |
Subscription approval confirmation was received. |
| 463 |
""" |
| 464 |
pass |
| 465 |
|
| 466 |
def unsubscribedReceived(self, presence): |
| 467 |
""" |
| 468 |
Unsubscription confirmation was received. |
| 469 |
""" |
| 470 |
pass |
| 471 |
|
| 472 |
def subscribeReceived(self, presence): |
| 473 |
""" |
| 474 |
Subscription request was received. |
| 475 |
""" |
| 476 |
pass |
| 477 |
|
| 478 |
def unsubscribeReceived(self, presence): |
| 479 |
""" |
| 480 |
Unsubscription request was received. |
| 481 |
""" |
| 482 |
pass |
| 483 |
|
| 484 |
def probeReceived(self, presence): |
| 485 |
""" |
| 486 |
Probe presence was received. |
| 487 |
""" |
| 488 |
pass |
| 489 |
|
| 490 |
def available( |
| 491 |
self, |
| 492 |
recipient=None, |
| 493 |
show=None, |
| 494 |
statuses=None, |
| 495 |
priority=0, |
| 496 |
status=None, |
| 497 |
sender=None, |
| 498 |
): |
| 499 |
""" |
| 500 |
Send available presence. |
| 501 |
|
| 502 |
@param recipient: Optional Recipient to which the presence should be |
| 503 |
sent. |
| 504 |
@type recipient: {JID} |
| 505 |
|
| 506 |
@param show: Optional detailed presence information. One of C{'away'}, |
| 507 |
C{'xa'}, C{'chat'}, C{'dnd'}. |
| 508 |
@type show: L{str} |
| 509 |
|
| 510 |
@param statuses: Mapping of natural language descriptions of the |
| 511 |
availability status, keyed by the language descriptor. A status |
| 512 |
without a language specified, is keyed with C{None}. |
| 513 |
@type statuses: L{dict} |
| 514 |
|
| 515 |
@param priority: priority level of the resource. |
| 516 |
@type priority: L{int} |
| 517 |
""" |
| 518 |
presence = AvailabilityPresence( |
| 519 |
recipient=recipient, |
| 520 |
sender=sender, |
| 521 |
show=show, |
| 522 |
statuses=statuses, |
| 523 |
status=status, |
| 524 |
priority=priority, |
| 525 |
) |
| 526 |
self.send(presence.toElement()) |
| 527 |
|
| 528 |
def unavailable(self, recipient=None, statuses=None, sender=None): |
| 529 |
""" |
| 530 |
Send unavailable presence. |
| 531 |
|
| 532 |
@param recipient: Optional entity to which the presence should be sent. |
| 533 |
@type recipient: {JID} |
| 534 |
|
| 535 |
@param statuses: dictionary of natural language descriptions of the |
| 536 |
availability status, keyed by the language descriptor. A status |
| 537 |
without a language specified, is keyed with C{None}. |
| 538 |
@type statuses: L{dict} |
| 539 |
""" |
| 540 |
presence = AvailabilityPresence( |
| 541 |
recipient=recipient, sender=sender, available=False, statuses=statuses |
| 542 |
) |
| 543 |
self.send(presence.toElement()) |
| 544 |
|
| 545 |
def subscribe(self, recipient, sender=None): |
| 546 |
""" |
| 547 |
Send subscription request |
| 548 |
|
| 549 |
@param recipient: Entity to subscribe to. |
| 550 |
@type recipient: {JID} |
| 551 |
""" |
| 552 |
presence = SubscriptionPresence(recipient=recipient, sender=sender) |
| 553 |
presence.stanzaType = "subscribe" |
| 554 |
self.send(presence.toElement()) |
| 555 |
|
| 556 |
def unsubscribe(self, recipient, sender=None): |
| 557 |
""" |
| 558 |
Send unsubscription request |
| 559 |
|
| 560 |
@param recipient: Entity to unsubscribe from. |
| 561 |
@type recipient: {JID} |
| 562 |
""" |
| 563 |
presence = SubscriptionPresence(recipient=recipient, sender=sender) |
| 564 |
presence.stanzaType = "unsubscribe" |
| 565 |
self.send(presence.toElement()) |
| 566 |
|
| 567 |
def subscribed(self, recipient, sender=None): |
| 568 |
""" |
| 569 |
Send subscription confirmation. |
| 570 |
|
| 571 |
@param recipient: Entity that subscribed. |
| 572 |
@type recipient: {JID} |
| 573 |
""" |
| 574 |
presence = SubscriptionPresence(recipient=recipient, sender=sender) |
| 575 |
presence.stanzaType = "subscribed" |
| 576 |
self.send(presence.toElement()) |
| 577 |
|
| 578 |
def unsubscribed(self, recipient, sender=None): |
| 579 |
""" |
| 580 |
Send unsubscription confirmation. |
| 581 |
|
| 582 |
@param recipient: Entity that unsubscribed. |
| 583 |
@type recipient: {JID} |
| 584 |
""" |
| 585 |
presence = SubscriptionPresence(recipient=recipient, sender=sender) |
| 586 |
presence.stanzaType = "unsubscribed" |
| 587 |
self.send(presence.toElement()) |
| 588 |
|
| 589 |
def probe(self, recipient, sender=None): |
| 590 |
""" |
| 591 |
Send presence probe. |
| 592 |
|
| 593 |
@param recipient: Entity to be probed. |
| 594 |
@type recipient: {JID} |
| 595 |
""" |
| 596 |
presence = ProbePresence(recipient=recipient, sender=sender) |
| 597 |
self.send(presence.toElement()) |
| 598 |
|
| 599 |
|
| 600 |
class RosterItem: |
| 601 |
""" |
| 602 |
Roster item. |
| 603 |
|
| 604 |
This represents one contact from an XMPP contact list known as roster. |
| 605 |
|
| 606 |
@ivar entity: The JID of the contact. |
| 607 |
@type entity: L{JID} |
| 608 |
@ivar name: The associated nickname for this contact. |
| 609 |
@type name: L{str} |
| 610 |
@ivar subscriptionTo: Subscription state to contact's presence. If C{True}, |
| 611 |
the roster owner is subscribed to the presence |
| 612 |
information of the contact. |
| 613 |
@type subscriptionTo: L{bool} |
| 614 |
@ivar subscriptionFrom: Contact's subscription state. If C{True}, the |
| 615 |
contact is subscribed to the presence information |
| 616 |
of the roster owner. |
| 617 |
@type subscriptionFrom: L{bool} |
| 618 |
@ivar pendingOut: Whether the subscription request to this contact is |
| 619 |
pending. |
| 620 |
@type pendingOut: L{bool} |
| 621 |
@ivar groups: Set of groups this contact is categorized in. Groups are |
| 622 |
represented by an opaque identifier of type L{str}. |
| 623 |
@type groups: L{set} |
| 624 |
@ivar approved: Signals pre-approved subscription. |
| 625 |
@type approved: L{bool} |
| 626 |
@ivar remove: Signals roster item removal. |
| 627 |
@type remove: L{bool} |
| 628 |
""" |
| 629 |
|
| 630 |
__subscriptionStates = { |
| 631 |
(False, False): None, |
| 632 |
(True, False): "to", |
| 633 |
(False, True): "from", |
| 634 |
(True, True): "both", |
| 635 |
} |
| 636 |
|
| 637 |
def __init__( |
| 638 |
self, entity, subscriptionTo=False, subscriptionFrom=False, name="", groups=None |
| 639 |
): |
| 640 |
self.entity = entity |
| 641 |
self.subscriptionTo = subscriptionTo |
| 642 |
self.subscriptionFrom = subscriptionFrom |
| 643 |
self.name = name |
| 644 |
self.groups = groups or set() |
| 645 |
|
| 646 |
self.pendingOut = False |
| 647 |
self.approved = False |
| 648 |
self.remove = False |
| 649 |
|
| 650 |
def toElement(self, rosterSet=False): |
| 651 |
""" |
| 652 |
Render to a DOM representation. |
| 653 |
|
| 654 |
If C{rosterSet} is set, some attributes, that may not be sent |
| 655 |
as a roster set, will not be rendered. |
| 656 |
|
| 657 |
@type rosterSet: C{boolean}. |
| 658 |
""" |
| 659 |
element = domish.Element((NS_ROSTER, "item")) |
| 660 |
element["jid"] = self.entity.full() |
| 661 |
|
| 662 |
if self.remove: |
| 663 |
subscription = "remove" |
| 664 |
else: |
| 665 |
if self.name: |
| 666 |
element["name"] = self.name |
| 667 |
|
| 668 |
if self.groups: |
| 669 |
for group in self.groups: |
| 670 |
element.addElement("group", content=group) |
| 671 |
|
| 672 |
if rosterSet: |
| 673 |
subscription = None |
| 674 |
else: |
| 675 |
subscription = self.__subscriptionStates[ |
| 676 |
self.subscriptionTo, self.subscriptionFrom |
| 677 |
] |
| 678 |
|
| 679 |
if self.pendingOut: |
| 680 |
element["ask"] = "subscribe" |
| 681 |
|
| 682 |
if self.approved: |
| 683 |
element["approved"] = "true" |
| 684 |
|
| 685 |
if subscription: |
| 686 |
element["subscription"] = subscription |
| 687 |
|
| 688 |
return element |
| 689 |
|
| 690 |
@classmethod |
| 691 |
def fromElement(Class, element): |
| 692 |
entity = JID(element["jid"]) |
| 693 |
item = Class(entity) |
| 694 |
subscription = element.getAttribute("subscription") |
| 695 |
if subscription == "remove": |
| 696 |
item.remove = True |
| 697 |
else: |
| 698 |
item.name = element.getAttribute("name", "") |
| 699 |
item.subscriptionTo = subscription in ("to", "both") |
| 700 |
item.subscriptionFrom = subscription in ("from", "both") |
| 701 |
item.pendingOut = element.getAttribute("ask") == "subscribe" |
| 702 |
item.approved = element.getAttribute("approved") in ("true", "1") |
| 703 |
for subElement in domish.generateElementsQNamed( |
| 704 |
element.children, "group", NS_ROSTER |
| 705 |
): |
| 706 |
item.groups.add(str(subElement)) |
| 707 |
return item |
| 708 |
|
| 709 |
|
| 710 |
class RosterRequest(Request): |
| 711 |
""" |
| 712 |
Roster request. |
| 713 |
|
| 714 |
@ivar item: Roster item to be set or pushed. |
| 715 |
@type item: L{RosterItem}. |
| 716 |
|
| 717 |
@ivar version: Roster version identifier for roster pushes and |
| 718 |
retrieving the roster as a delta from a known cached version. This |
| 719 |
should only be set if the recipient is known to support roster |
| 720 |
versioning. |
| 721 |
@type version: L{str} |
| 722 |
|
| 723 |
@ivar rosterSet: If set, this is a roster set request. This flag is used |
| 724 |
to make sure some attributes of the roster item are not rendered by |
| 725 |
L{toElement}. |
| 726 |
@type roster: C{boolean} |
| 727 |
""" |
| 728 |
|
| 729 |
item = None |
| 730 |
version = None |
| 731 |
rosterSet = False |
| 732 |
|
| 733 |
def parseRequest(self, element): |
| 734 |
self.version = element.getAttribute("ver") |
| 735 |
|
| 736 |
for child in element.elements(NS_ROSTER, "item"): |
| 737 |
self.item = RosterItem.fromElement(child) |
| 738 |
break |
| 739 |
|
| 740 |
def toElement(self): |
| 741 |
element = Request.toElement(self) |
| 742 |
query = element.addElement((NS_ROSTER, "query")) |
| 743 |
if self.version is not None: |
| 744 |
query["ver"] = self.version |
| 745 |
if self.item: |
| 746 |
query.addChild(self.item.toElement(rosterSet=self.rosterSet)) |
| 747 |
return element |
| 748 |
|
| 749 |
|
| 750 |
class RosterPushIgnored(Exception): |
| 751 |
""" |
| 752 |
Raised when this entity doesn't want to accept/trust a roster push. |
| 753 |
|
| 754 |
To avert presence leaks, a handler can raise L{RosterPushIgnored} when |
| 755 |
not accepting a roster push (directly or via Deferred). This will |
| 756 |
result in a C{'service-unavailable'} error being sent in return. |
| 757 |
""" |
| 758 |
|
| 759 |
|
| 760 |
class Roster(dict): |
| 761 |
""" |
| 762 |
In-memory roster container. |
| 763 |
|
| 764 |
This provides a roster as a mapping from L{JID} to L{RosterItem}. If |
| 765 |
roster versioning is used, the C{version} attribute holds the version |
| 766 |
identifier for this version of the roster. |
| 767 |
|
| 768 |
@ivar version: Roster version identifier. |
| 769 |
@type version: L{str}. |
| 770 |
""" |
| 771 |
|
| 772 |
version = None |
| 773 |
|
| 774 |
|
| 775 |
class RosterClientProtocol(XMPPHandler, IQHandlerMixin): |
| 776 |
""" |
| 777 |
Client side XMPP roster protocol. |
| 778 |
|
| 779 |
The roster can be retrieved using L{getRoster}. Subsequent changes to the |
| 780 |
roster will be pushed, resulting in calls to L{setReceived} or |
| 781 |
L{removeReceived}. These methods should be overridden to handle the |
| 782 |
roster pushes. |
| 783 |
|
| 784 |
RFC 6121 specifically allows entities other than a user's server to |
| 785 |
hold a roster for that user. However, how a client should deal with |
| 786 |
that is currently not yet specfied. |
| 787 |
|
| 788 |
By default roster pushes from other source. I.e. when C{request.sender} |
| 789 |
is set but the sender's bare JID is different from the user's bare JID. |
| 790 |
Set L{allowAnySender} to allow roster pushes from any sender. To |
| 791 |
avert presence leaks, L{RosterPushIgnored} should then be raised for |
| 792 |
pushes from untrusted senders. |
| 793 |
|
| 794 |
If roster versioning is supported by the server, the roster and |
| 795 |
subsequent pushes are annotated with a version identifier. This can be |
| 796 |
used to cache the roster on the client side. Upon reconnect, the client |
| 797 |
can request the roster with the version identifier of the cached version. |
| 798 |
The server may then choose to only send roster pushes for the changes |
| 799 |
since that version, instead of a complete roster. |
| 800 |
|
| 801 |
@cvar allowAnySender: Flag to allow roster pushes from any sender. |
| 802 |
C{False} by default. |
| 803 |
@type allowAnySender: C{boolean} |
| 804 |
""" |
| 805 |
|
| 806 |
allowAnySender = False |
| 807 |
iqHandlers = {XPATH_ROSTER_SET: "_onRosterSet"} |
| 808 |
|
| 809 |
def connectionInitialized(self): |
| 810 |
self.xmlstream.addObserver(XPATH_ROSTER_SET, self.handleRequest) |
| 811 |
|
| 812 |
def getRoster(self, version: str | None = None) -> defer.Deferred[Roster | None]: |
| 813 |
""" |
| 814 |
Retrieve contact list. |
| 815 |
|
| 816 |
The returned deferred fires with the result of the roster request as |
| 817 |
L{Roster}, a mapping from contact JID to L{RosterItem}. |
| 818 |
|
| 819 |
If roster versioning is supported, the recipient responds with either |
| 820 |
a the complete roster or with an empty result. In case of complete |
| 821 |
roster, the L{Roster} is annotated with a C{version} attribute that |
| 822 |
holds the version identifier for this version of the roster. This |
| 823 |
identifier should be used for caching. |
| 824 |
|
| 825 |
If the recipient responds with an empty result, the returned deferred |
| 826 |
fires with C{None}. This indicates that any roster modifications |
| 827 |
since C{version} will be sent as roster pushes. |
| 828 |
|
| 829 |
Note that the empty result (C{None}) is different from an empty |
| 830 |
roster (L{Roster} with no items). |
| 831 |
|
| 832 |
@param version: Optional version identifier of the last cashed |
| 833 |
version of the roster. This shall only be set if the recipient is |
| 834 |
known to support roster versioning. If there is no (valid) cached |
| 835 |
version of the roster, but roster versioning is desired, |
| 836 |
C{version} should be set to the empty string (C{u''}). |
| 837 |
|
| 838 |
@return: Roster as a mapping from L{JID} to L{RosterItem}. |
| 839 |
""" |
| 840 |
|
| 841 |
def processRoster(result): |
| 842 |
if result.query is not None: |
| 843 |
roster = Roster() |
| 844 |
roster.version = result.query.getAttribute("ver") |
| 845 |
for element in result.query.elements(NS_ROSTER, "item"): |
| 846 |
item = RosterItem.fromElement(element) |
| 847 |
roster[item.entity] = item |
| 848 |
return roster |
| 849 |
else: |
| 850 |
return None |
| 851 |
|
| 852 |
request = RosterRequest(stanzaType="get") |
| 853 |
request.version = version |
| 854 |
d = self.request(request) |
| 855 |
d.addCallback(processRoster) |
| 856 |
return d |
| 857 |
|
| 858 |
def setItem(self, item): |
| 859 |
""" |
| 860 |
Add or modify a roster item. |
| 861 |
|
| 862 |
Note that RFC 6121 doesn't allow all properties of a roster item to |
| 863 |
be sent when setting a roster item. Only the C{name} and C{groups} |
| 864 |
attributes from C{item} are sent to the server. Presence subscription |
| 865 |
management must be done through L{PresenceProtocol}. |
| 866 |
|
| 867 |
@param item: The roster item to be set. |
| 868 |
@type item: L{RosterItem}. |
| 869 |
|
| 870 |
@rtype: L{twisted.internet.defer.Deferred} |
| 871 |
""" |
| 872 |
request = RosterRequest(stanzaType="set") |
| 873 |
request.rosterSet = True |
| 874 |
request.item = item |
| 875 |
return self.request(request) |
| 876 |
|
| 877 |
def removeItem(self, entity): |
| 878 |
""" |
| 879 |
Remove an item from the contact list. |
| 880 |
|
| 881 |
@param entity: The contact to remove the roster item for. |
| 882 |
@type entity: L{JID<twisted.words.protocols.jabber.jid.JID>} |
| 883 |
|
| 884 |
@rtype: L{twisted.internet.defer.Deferred} |
| 885 |
""" |
| 886 |
item = RosterItem(entity) |
| 887 |
item.remove = True |
| 888 |
return self.setItem(item) |
| 889 |
|
| 890 |
def _onRosterSet(self, iq): |
| 891 |
def trapIgnored(failure): |
| 892 |
failure.trap(RosterPushIgnored) |
| 893 |
raise error.StanzaError("service-unavailable") |
| 894 |
|
| 895 |
request = RosterRequest.fromElement(iq) |
| 896 |
|
| 897 |
if ( |
| 898 |
not self.allowAnySender |
| 899 |
and request.sender |
| 900 |
and request.sender.userhostJID() != self.parent.jid.userhostJID() |
| 901 |
): |
| 902 |
d = defer.fail(RosterPushIgnored()) |
| 903 |
elif request.item.remove: |
| 904 |
d = defer.maybeDeferred(self.removeReceived, request) |
| 905 |
else: |
| 906 |
d = defer.maybeDeferred(self.setReceived, request) |
| 907 |
d.addErrback(trapIgnored) |
| 908 |
return d |
| 909 |
|
| 910 |
def setReceived(self, request): |
| 911 |
""" |
| 912 |
Called when a roster push for a new or update item was received. |
| 913 |
|
| 914 |
@param request: The push request. |
| 915 |
@type request: L{RosterRequest} |
| 916 |
""" |
| 917 |
|
| 918 |
def removeReceived(self, request): |
| 919 |
""" |
| 920 |
Called when a roster push for the removal of an item was received. |
| 921 |
|
| 922 |
@param request: The push request. |
| 923 |
@type request: L{RosterRequest} |
| 924 |
""" |
| 925 |
|
| 926 |
|
| 927 |
class Message(Stanza): |
| 928 |
""" |
| 929 |
A message stanza. |
| 930 |
""" |
| 931 |
|
| 932 |
stanzaKind = "message" |
| 933 |
|
| 934 |
childParsers = { |
| 935 |
(None, "body"): "_childParser_body", |
| 936 |
(None, "subject"): "_childParser_subject", |
| 937 |
} |
| 938 |
|
| 939 |
def __init__(self, recipient=None, sender=None, body=None, subject=None): |
| 940 |
Stanza.__init__(self, recipient, sender) |
| 941 |
self.body = body |
| 942 |
self.subject = subject |
| 943 |
|
| 944 |
def _childParser_body(self, element): |
| 945 |
self.body = str(element) |
| 946 |
|
| 947 |
def _childParser_subject(self, element): |
| 948 |
self.subject = str(element) |
| 949 |
|
| 950 |
def toElement(self): |
| 951 |
element = Stanza.toElement(self) |
| 952 |
|
| 953 |
if self.body: |
| 954 |
element.addElement("body", content=self.body) |
| 955 |
if self.subject: |
| 956 |
element.addElement("subject", content=self.subject) |
| 957 |
|
| 958 |
return element |
| 959 |
|
| 960 |
|
| 961 |
class MessageProtocol(XMPPHandler): |
| 962 |
""" |
| 963 |
Generic XMPP subprotocol handler for incoming message stanzas. |
| 964 |
""" |
| 965 |
|
| 966 |
messageTypes = None, "normal", "chat", "headline", "groupchat" |
| 967 |
|
| 968 |
def connectionInitialized(self): |
| 969 |
self.xmlstream.addObserver("/message", self._onMessage) |
| 970 |
|
| 971 |
def _onMessage(self, message: domish.Element) -> None: |
| 972 |
if message.handled: |
| 973 |
return |
| 974 |
|
| 975 |
messageType = message.getAttribute("type") |
| 976 |
|
| 977 |
if messageType == "error": |
| 978 |
return |
| 979 |
|
| 980 |
if messageType not in self.messageTypes: |
| 981 |
message["type"] = "normal" |
| 982 |
|
| 983 |
self.onMessage(message) |
| 984 |
|
| 985 |
def onMessage(self, message: domish.Element) -> None: |
| 986 |
""" |
| 987 |
Called when a message stanza was received. |
| 988 |
""" |