Debian Codegraph @

tx_xmpp/muc.py

raw
1 # -*- test-case-name: tx_xmpp.test.test.test_muc -*-
2 #
3 # Copyright (c) Ralph Meijer.
4 # See LICENSE for details.
5
6 """
7 XMPP Multi-User Chat protocol.
8
9 This protocol is specified in
10 U{XEP-0045<http://xmpp.org/extensions/xep-0045.html>}.
11 """
12
13 from constantly import ValueConstant, Values
14 from dateutil.tz import tzutc
15 from twisted.internet import defer
16 from twisted.internet.interfaces import IReactorTime
17 from twisted.python.failure import Failure
18 from twisted.words.protocols.jabber import error, jid, xmlstream
19 from twisted.words.xish import domish
20 from zope.interface import implementer
21
22 from . import data_form, generic, itx_xmpp, xmppim
23 from .delay import Delay, DelayMixin
24 from .itx_xmpp import IMUCClient
25 from .subprotocols import XMPPHandler
26
27 # Multi User Chat namespaces
28 NS_MUC = "http://jabber.org/protocol/muc"
29 NS_MUC_USER = NS_MUC + "#user"
30 NS_MUC_ADMIN = NS_MUC + "#admin"
31 NS_MUC_OWNER = NS_MUC + "#owner"
32 NS_MUC_ROOMINFO = NS_MUC + "#roominfo"
33 NS_MUC_CONFIG = NS_MUC + "#roomconfig"
34 NS_MUC_REQUEST = NS_MUC + "#request"
35 NS_MUC_REGISTER = NS_MUC + "#register"
36
37 NS_REGISTER = "jabber:iq:register"
38
39 MESSAGE = "/message"
40 PRESENCE = "/presence"
41
42 GROUPCHAT = MESSAGE + '[@type="groupchat"]'
43
44 DEFER_TIMEOUT = 30 # basic timeout is 30 seconds
45
46
47 class STATUS_CODE(Values):
48 REALJID_PUBLIC = ValueConstant(100)
49 AFFILIATION_CHANGED = ValueConstant(101)
50 UNAVAILABLE_SHOWN = ValueConstant(102)
51 UNAVAILABLE_NOT_SHOWN = ValueConstant(103)
52 CONFIGURATION_CHANGED = ValueConstant(104)
53 SELF_PRESENCE = ValueConstant(110)
54 LOGGING_ENABLED = ValueConstant(170)
55 LOGGING_DISABLED = ValueConstant(171)
56 NON_ANONYMOUS = ValueConstant(172)
57 SEMI_ANONYMOUS = ValueConstant(173)
58 FULLY_ANONYMOUS = ValueConstant(174)
59 ROOM_CREATED = ValueConstant(201)
60 NICK_ASSIGNED = ValueConstant(210)
61 BANNED = ValueConstant(301)
62 NEW_NICK = ValueConstant(303)
63 KICKED = ValueConstant(307)
64 REMOVED_AFFILIATION = ValueConstant(321)
65 REMOVED_MEMBERSHIP = ValueConstant(322)
66 REMOVED_SHUTDOWN = ValueConstant(332)
67
68
69 @implementer(itx_xmpp.IMUCStatuses)
70 class Statuses(set):
71 """
72 Container of MUC status conditions.
73
74 This is currently implemented as a set of constant values from
75 L{STATUS_CODE}. Instances of this class provide L{IMUCStatuses}, that
76 defines the supported operations. Even though this class currently derives
77 from L{set}, future versions might not. This provides an upgrade path to
78 cater for extensible status conditions, as defined in
79 U{XEP-0306<http://xmpp.org/extensions/xep-0306.html>}.
80 """
81
82
83 class _FormRequest(generic.Request):
84 """
85 Base class for form exchange requests.
86 """
87
88 requestNamespace = None
89 formNamespace = None
90
91 def __init__(self, recipient, sender=None, options=None):
92 if options is None:
93 stanzaType = "get"
94 else:
95 stanzaType = "set"
96
97 generic.Request.__init__(self, recipient, sender, stanzaType)
98 self.options = options
99
100 def toElement(self):
101 element = generic.Request.toElement(self)
102
103 query = element.addElement((self.requestNamespace, "query"))
104 if self.options is None:
105 # This is a request for the configuration form.
106 form = None
107 elif self.options is False:
108 form = data_form.Form(formType="cancel")
109 else:
110 form = data_form.Form(formType="submit", formNamespace=self.formNamespace)
111 form.makeFields(self.options)
112
113 if form is not None:
114 query.addChild(form.toElement())
115
116 return element
117
118
119 class ConfigureRequest(_FormRequest):
120 """
121 Configure MUC room request.
122
123 http://xmpp.org/extensions/xep-0045.html#roomconfig
124 """
125
126 requestNamespace = NS_MUC_OWNER
127 formNamespace = NS_MUC_CONFIG
128
129
130 class RegisterRequest(_FormRequest):
131 """
132 Register request.
133
134 http://xmpp.org/extensions/xep-0045.html#register
135 """
136
137 requestNamespace = NS_REGISTER
138 formNamespace = NS_MUC_REGISTER
139
140
141 class AdminItem:
142 """
143 Item representing role and/or affiliation for admin request.
144 """
145
146 def __init__(self, affiliation=None, role=None, entity=None, nick=None, reason=None):
147 self.affiliation = affiliation
148 self.role = role
149 self.entity = entity
150 self.nick = nick
151 self.reason = reason
152
153 def toElement(self):
154 element = domish.Element((NS_MUC_ADMIN, "item"))
155
156 if self.entity:
157 element["jid"] = self.entity.full()
158
159 if self.nick:
160 element["nick"] = self.nick
161
162 if self.affiliation:
163 element["affiliation"] = self.affiliation
164
165 if self.role:
166 element["role"] = self.role
167
168 if self.reason:
169 element.addElement("reason", content=self.reason)
170
171 return element
172
173 @classmethod
174 def fromElement(Class, element):
175 item = Class()
176
177 if element.hasAttribute("jid"):
178 item.entity = jid.JID(element["jid"])
179
180 item.nick = element.getAttribute("nick")
181 item.affiliation = element.getAttribute("affiliation")
182 item.role = element.getAttribute("role")
183
184 for child in element.elements(NS_MUC_ADMIN, "reason"):
185 item.reason = str(child)
186
187 return item
188
189
190 class AdminStanza(generic.Request):
191 """
192 An admin request or response.
193 """
194
195 childParsers = {(NS_MUC_ADMIN, "query"): "_childParser_query"}
196
197 def toElement(self):
198 element = generic.Request.toElement(self)
199 element.addElement((NS_MUC_ADMIN, "query"))
200
201 if self.items:
202 for item in self.items:
203 element.query.addChild(item.toElement())
204
205 return element
206
207 def _childParser_query(self, element):
208 self.items = []
209 for child in element.elements(NS_MUC_ADMIN, "item"):
210 self.items.append(AdminItem.fromElement(child))
211
212
213 class DestructionRequest(generic.Request):
214 """
215 Room destruction request.
216
217 @param reason: Optional reason for the destruction of this room.
218 @type reason: L{str}.
219
220 @param alternate: Optional room JID of an alternate venue.
221 @type alternate: L{JID<twisted.words.protocols.jabber.jid.JID>}
222
223 @param password: Optional password for entering the alternate venue.
224 @type password: L{str}
225 """
226
227 stanzaType = "set"
228
229 def __init__(
230 self, recipient, sender=None, reason=None, alternate=None, password=None
231 ):
232 generic.Request.__init__(self, recipient, sender)
233 self.reason = reason
234 self.alternate = alternate
235 self.password = password
236
237 def toElement(self):
238 element = generic.Request.toElement(self)
239 element.addElement((NS_MUC_OWNER, "query"))
240 element.query.addElement("destroy")
241
242 if self.alternate:
243 element.query.destroy["jid"] = self.alternate.full()
244
245 if self.password:
246 element.query.destroy.addElement("password", content=self.password)
247
248 if self.reason:
249 element.query.destroy.addElement("reason", content=self.reason)
250
251 return element
252
253
254 class GroupChat(xmppim.Message, DelayMixin):
255 """
256 A groupchat message.
257 """
258
259 stanzaType = "groupchat"
260
261 def toElement(self, legacyDelay=False):
262 """
263 Render into a domish Element.
264
265 @param legacyDelay: If L{True} send the delayed delivery information
266 in legacy format.
267 """
268 element = xmppim.Message.toElement(self)
269
270 if self.delay:
271 element.addChild(self.delay.toElement(legacy=legacyDelay))
272
273 return element
274
275
276 class PrivateChat(xmppim.Message):
277 """
278 A chat message.
279 """
280
281 stanzaType = "chat"
282
283
284 class InviteMessage(xmppim.Message):
285
286 def __init__(self, recipient=None, sender=None, invitee=None, reason=None):
287 xmppim.Message.__init__(self, recipient, sender)
288 self.invitee = invitee
289 self.reason = reason
290
291 def toElement(self):
292 element = xmppim.Message.toElement(self)
293
294 child = element.addElement((NS_MUC_USER, "x"))
295 child.addElement("invite")
296 child.invite["to"] = self.invitee.full()
297
298 if self.reason:
299 child.invite.addElement("reason", content=self.reason)
300
301 return element
302
303
304 class HistoryOptions:
305 """
306 A history configuration object.
307
308 @ivar maxchars: Limit the total number of characters in the history to "X"
309 (where the character count is the characters of the complete XML
310 stanzas, not only their XML character data).
311 @type maxchars: L{int}
312
313 @ivar maxstanzas: Limit the total number of messages in the history to "X".
314 @type mazstanzas: L{int}
315
316 @ivar seconds: Send only the messages received in the last "X" seconds.
317 @type seconds: L{int}
318
319 @ivar since: Send only the messages received since the datetime specified.
320 Note that this must be an offset-aware instance.
321 @type since: L{datetime.datetime}
322 """
323
324 attributes = ["maxChars", "maxStanzas", "seconds", "since"]
325
326 def __init__(self, maxChars=None, maxStanzas=None, seconds=None, since=None):
327 self.maxChars = maxChars
328 self.maxStanzas = maxStanzas
329 self.seconds = seconds
330 self.since = since
331
332 def toElement(self):
333 """
334 Returns a L{domish.Element} representing the history options.
335 """
336 element = domish.Element((NS_MUC, "history"))
337
338 for key in self.attributes:
339 value = getattr(self, key, None)
340 if value is not None:
341 if key == "since":
342 stamp = value.astimezone(tzutc())
343 element[key] = stamp.strftime("%Y-%m-%dT%H:%M:%SZ")
344 else:
345 element[key.lower()] = str(value)
346
347 return element
348
349
350 class BasicPresence(xmppim.AvailabilityPresence):
351 """
352 Availability presence sent from MUC client to service.
353
354 @type history: L{HistoryOptions}
355 """
356
357 history = None
358 password = None
359
360 def toElement(self):
361 element = xmppim.AvailabilityPresence.toElement(self)
362
363 muc = element.addElement((NS_MUC, "x"))
364 if self.password:
365 muc.addElement("password", content=self.password)
366 if self.history:
367 muc.addChild(self.history.toElement())
368
369 return element
370
371
372 class UserPresence(xmppim.AvailabilityPresence):
373 """
374 Availability presence sent from MUC service to client.
375
376 @ivar affiliation: Affiliation of the entity to the room.
377 @type affiliation: L{str}
378
379 @ivar role: Role of the entity in the room.
380 @type role: L{str}
381
382 @ivar entity: The real JID of the entity this presence is from.
383 @type entity: L{JID<twisted.words.protocols.jabber.jid.JID>}
384
385 @ivar mucStatuses: Set of one or more status codes from L{STATUS_CODE}.
386 See L{Statuses} for usage notes.
387 @type mucStatuses: L{Statuses}
388
389 @ivar nick: The nick name of the entity in the room.
390 @type nick: L{str}
391 """
392
393 affiliation: str | None = None
394 role: str | None = None
395 entity: jid.JID | None = None
396 nick: str | None = None
397
398 mucStatuses: Statuses
399
400 childParsers = {(NS_MUC_USER, "x"): "_childParser_mucUser"}
401
402 def __init__(self, *args, **kwargs):
403 self.mucStatuses = Statuses()
404 xmppim.AvailabilityPresence.__init__(self, *args, **kwargs)
405
406 def _childParser_mucUser(self, element):
407 """
408 Parse the MUC user extension element.
409 """
410 for child in element.elements():
411 if child.uri != NS_MUC_USER:
412 continue
413
414 elif child.name == "status":
415 try:
416 value = int(child.getAttribute("code"))
417 statusCode = STATUS_CODE.lookupByValue(value)
418 except (TypeError, ValueError):
419 continue
420
421 self.mucStatuses.add(statusCode)
422
423 elif child.name == "item":
424 if child.hasAttribute("jid"):
425 self.entity = jid.JID(child["jid"])
426
427 self.nick = child.getAttribute("nick")
428 self.affiliation = child.getAttribute("affiliation")
429 self.role = child.getAttribute("role")
430
431 for reason in child.elements(NS_MUC_ADMIN, "reason"):
432 self.reason = str(reason)
433
434 # TODO: destroy
435
436
437 class VoiceRequest(xmppim.Message):
438 """
439 Voice request message.
440 """
441
442 def toElement(self):
443 element = xmppim.Message.toElement(self)
444
445 # build data form
446 form = data_form.Form("submit", formNamespace=NS_MUC_REQUEST)
447 form.addField(
448 data_form.Field(var="muc#role", value="participant", label="Requested role")
449 )
450 element.addChild(form.toElement())
451
452 return element
453
454
455 class MUCClientProtocol(xmppim.BasePresenceProtocol):
456 """
457 Multi-User Chat client protocol.
458 """
459
460 timeout = None
461
462 presenceTypeParserMap = {
463 "error": generic.ErrorStanza,
464 "available": UserPresence,
465 "unavailable": UserPresence,
466 }
467
468 def __init__(self, reactor=None):
469 XMPPHandler.__init__(self)
470
471 if reactor:
472 self._reactor = reactor
473 else:
474 from twisted.internet import reactor
475
476 self._reactor = reactor
477
478 def connectionInitialized(self):
479 """
480 Called when the XML stream has been initialized.
481
482 It initializes several XPath events to handle MUC stanzas that come
483 in.
484 """
485 xmppim.BasePresenceProtocol.connectionInitialized(self)
486 self.xmlstream.addObserver(GROUPCHAT, self._onGroupChat)
487 self._roomOccupantMap = {}
488
489 def _onGroupChat(self, element):
490 """
491 A group chat message has been received from a MUC room.
492
493 There are a few event methods that may get called here.
494 L{receivedGroupChat}, L{receivedSubject} or L{receivedHistory}.
495 """
496 message = GroupChat.fromElement(element)
497 self.groupChatReceived(message)
498
499 def groupChatReceived(self, message):
500 """
501 Called when a groupchat message was received.
502
503 This method is called with a parsed representation of a received
504 groupchat message and can be overridden for further processing.
505
506 For regular groupchat message, the C{body} attribute contains the
507 message body. Conversation history sent by the room upon joining, will
508 have the C{delay} attribute set, room subject changes the C{subject}
509 attribute. See L{GroupChat} for details.
510
511 @param message: Groupchat message.
512 @type message: L{GroupChat}
513 """
514 pass
515
516 def _sendDeferred(self, stanza):
517 """
518 Send presence stanza, adding a deferred with a timeout.
519
520 @param stanza: The presence stanza to send over the wire.
521 @type stanza: L{generic.Stanza}
522
523 @param timeout: The number of seconds to wait before the deferred is
524 timed out.
525 @type timeout: L{int}
526
527 The deferred object L{defer.Deferred} is returned.
528 """
529
530 def onResponse(element):
531 if element.getAttribute("type") == "error":
532 d.errback(error.exceptionFromStanza(element))
533 else:
534 d.callback(UserPresence.fromElement(element))
535
536 def onTimeout():
537 d.errback(xmlstream.TimeoutError("Timeout waiting for response."))
538
539 def cancelTimeout(result):
540 if call.active():
541 call.cancel()
542
543 return result
544
545 def recordOccupant(presence):
546 occupantJID = presence.sender
547 roomJID = occupantJID.userhostJID()
548 self._roomOccupantMap[roomJID] = occupantJID
549 return presence
550
551 call = self._reactor.callLater(DEFER_TIMEOUT, onTimeout)
552
553 d = defer.Deferred()
554 d.addBoth(cancelTimeout)
555 d.addCallback(recordOccupant)
556
557 query = "/presence[@from='%s' or (@from='%s' and @type='error')]" % (
558 stanza.recipient.full(),
559 stanza.recipient.userhost(),
560 )
561 self.xmlstream.addOnetimeObserver(query, onResponse, priority=-1)
562 self.xmlstream.send(stanza.toElement())
563 return d
564
565 def join(self, roomJID, nick, historyOptions=None, password=None):
566 """
567 Join a MUC room by sending presence to it.
568
569 @param roomJID: The JID of the room the entity is joining.
570 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
571
572 @param nick: The nick name for the entitity joining the room.
573 @type nick: L{str}
574
575 @param historyOptions: Options for conversation history sent by the
576 room upon joining.
577 @type historyOptions: L{HistoryOptions}
578
579 @param password: Optional password for the room.
580 @type password: L{str}
581
582 @return: A deferred that fires when the entity is in the room or an
583 error has occurred.
584 """
585 occupantJID = jid.JID(tuple=(roomJID.user, roomJID.host, nick))
586
587 presence = BasicPresence(recipient=occupantJID)
588 if password:
589 presence.password = password
590 if historyOptions:
591 presence.history = historyOptions
592
593 return self._sendDeferred(presence)
594
595 def nick(self, roomJID, nick):
596 """
597 Change an entity's nick name in a MUC room.
598
599 See: http://xmpp.org/extensions/xep-0045.html#changenick
600
601 @param roomJID: The JID of the room.
602 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
603
604 @param nick: The new nick name within the room.
605 @type nick: L{str}
606 """
607 occupantJID = jid.JID(tuple=(roomJID.user, roomJID.host, nick))
608 presence = BasicPresence(recipient=occupantJID)
609 return self._sendDeferred(presence)
610
611 def status(self, roomJID, show=None, status=None):
612 """
613 Change user status.
614
615 See: http://xmpp.org/extensions/xep-0045.html#changepres
616
617 @param roomJID: The Room JID of the room.
618 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
619
620 @param show: The availability of the entity. Common values are xa,
621 available, etc
622 @type show: L{str}
623
624 @param status: The current status of the entity.
625 @type status: L{str}
626 """
627 occupantJID = self._roomOccupantMap[roomJID]
628 presence = BasicPresence(recipient=occupantJID, show=show, status=status)
629 return self._sendDeferred(presence)
630
631 def leave(self, roomJID):
632 """
633 Leave a MUC room.
634
635 See: http://xmpp.org/extensions/xep-0045.html#exit
636
637 @param roomJID: The JID of the room.
638 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
639 """
640 occupantJID = self._roomOccupantMap[roomJID]
641 presence = xmppim.AvailabilityPresence(recipient=occupantJID, available=False)
642
643 return self._sendDeferred(presence)
644
645 def groupChat(self, roomJID, body):
646 """
647 Send a groupchat message.
648 """
649 message = GroupChat(recipient=roomJID, body=body)
650 self.send(message.toElement())
651
652 def chat(self, occupantJID, body):
653 """
654 Send a private chat message to a user in a MUC room.
655
656 See: http://xmpp.org/extensions/xep-0045.html#privatemessage
657
658 @param occupantJID: The Room JID of the other user.
659 @type occupantJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
660 """
661 message = PrivateChat(recipient=occupantJID, body=body)
662 self.send(message.toElement())
663
664 def subject(self, roomJID, subject):
665 """
666 Change the subject of a MUC room.
667
668 See: http://xmpp.org/extensions/xep-0045.html#subject-mod
669
670 @param roomJID: The bare JID of the room.
671 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
672
673 @param subject: The subject you want to set.
674 @type subject: L{str}
675 """
676 message = GroupChat(roomJID.userhostJID(), subject=subject)
677 self.send(message.toElement())
678
679 def invite(self, roomJID, invitee, reason=None):
680 """
681 Invite a xmpp entity to a MUC room.
682
683 See: http://xmpp.org/extensions/xep-0045.html#invite
684
685 @param roomJID: The bare JID of the room.
686 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
687
688 @param invitee: The entity that is being invited.
689 @type invitee: L{JID<twisted.words.protocols.jabber.jid.JID>}
690
691 @param reason: The reason for the invite.
692 @type reason: L{str}
693 """
694 message = InviteMessage(recipient=roomJID, invitee=invitee, reason=reason)
695 self.send(message.toElement())
696
697 def getRegisterForm(self, roomJID):
698 """
699 Grab the registration form for a MUC room.
700
701 @param room: The room jabber/xmpp entity id for the requested
702 registration form.
703 @type room: L{JID<twisted.words.protocols.jabber.jid.JID>}
704 """
705
706 def cb(response):
707 form = data_form.findForm(response.query, NS_MUC_REGISTER)
708 return form
709
710 request = RegisterRequest(recipient=roomJID, options=None)
711 d = self.request(request)
712 d.addCallback(cb)
713 return d
714
715 def register(self, roomJID, options):
716 """
717 Send a request to register for a room.
718
719 @param roomJID: The bare JID of the room.
720 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
721
722 @param options: A mapping of field names to values, or L{None} to
723 cancel.
724 @type options: L{dict}
725 """
726 if options is None:
727 options = False
728 request = RegisterRequest(recipient=roomJID, options=options)
729 return self.request(request)
730
731 def voice(self, roomJID):
732 """
733 Request voice for a moderated room.
734
735 @param roomJID: The room jabber/xmpp entity id.
736 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
737 """
738 message = VoiceRequest(recipient=roomJID)
739 self.xmlstream.send(message.toElement())
740
741 def history(self, roomJID, messages):
742 """
743 Send history to create a MUC based on a one on one chat.
744
745 See: http://xmpp.org/extensions/xep-0045.html#continue
746
747 @param roomJID: The room jabber/xmpp entity id.
748 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
749
750 @param messages: The history to send to the room as an ordered list of
751 message, represented by a dictionary with the keys
752 L{'stanza'}, holding the original stanza a
753 L{domish.Element}, and L{'timestamp'} with the
754 timestamp.
755 @type messages: L{list} of L{domish.Element}
756 """
757
758 for message in messages:
759 stanza = message["stanza"]
760 stanza["type"] = "groupchat"
761
762 delay = Delay(stamp=message["timestamp"])
763
764 sender = stanza.getAttribute("from")
765 if sender is not None:
766 delay.sender = jid.JID(sender)
767
768 stanza.addChild(delay.toElement())
769
770 stanza["to"] = roomJID.userhost()
771 if stanza.hasAttribute("from"):
772 del stanza["from"]
773
774 self.xmlstream.send(stanza)
775
776 def getConfiguration(self, roomJID):
777 """
778 Grab the configuration from the room.
779
780 This sends an iq request to the room.
781
782 @param roomJID: The bare JID of the room.
783 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
784
785 @return: A deferred that fires with the room's configuration form as
786 a L{data_form.Form} or L{None} if there are no configuration
787 options available.
788 """
789
790 def cb(response):
791 form = data_form.findForm(response.query, NS_MUC_CONFIG)
792 return form
793
794 request = ConfigureRequest(recipient=roomJID, options=None)
795 d = self.request(request)
796 d.addCallback(cb)
797 return d
798
799 def configure(self, roomJID, options):
800 """
801 Configure a room.
802
803 @param roomJID: The room to configure.
804 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
805
806 @param options: A mapping of field names to values, or L{None} to
807 cancel.
808 @type options: L{dict}
809 """
810 if options is None:
811 options = False
812 request = ConfigureRequest(recipient=roomJID, options=options)
813 return self.request(request)
814
815 def _getAffiliationList(self, roomJID, affiliation):
816 """
817 Send a request for an affiliation list in a room.
818 """
819
820 def cb(response):
821 stanza = AdminStanza.fromElement(response)
822 return stanza.items
823
824 request = AdminStanza(recipient=roomJID, stanzaType="get")
825 request.items = [AdminItem(affiliation=affiliation)]
826 d = self.request(request)
827 d.addCallback(cb)
828 return d
829
830 def _getRoleList(self, roomJID, role):
831 """
832 Send a request for a role list in a room.
833 """
834
835 def cb(response):
836 stanza = AdminStanza.fromElement(response)
837 return stanza.items
838
839 request = AdminStanza(recipient=roomJID, stanzaType="get")
840 request.items = [AdminItem(role=role)]
841 d = self.request(request)
842 d.addCallback(cb)
843 return d
844
845 def getMemberList(self, roomJID):
846 """
847 Get the member list of a room.
848
849 @param roomJID: The bare JID of the room.
850 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
851 """
852 return self._getAffiliationList(roomJID, "member")
853
854 def getAdminList(self, roomJID):
855 """
856 Get the admin list of a room.
857
858 @param roomJID: The bare JID of the room.
859 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
860 """
861 return self._getAffiliationList(roomJID, "admin")
862
863 def getBanList(self, roomJID):
864 """
865 Get an outcast list from a room.
866
867 @param roomJID: The bare JID of the room.
868 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
869 """
870 return self._getAffiliationList(roomJID, "outcast")
871
872 def getOwnerList(self, roomJID):
873 """
874 Get an owner list from a room.
875
876 @param roomJID: The bare JID of the room.
877 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
878 """
879 return self._getAffiliationList(roomJID, "owner")
880
881 def getModeratorList(self, roomJID):
882 """
883 Get the moderator list of a room.
884
885 @param roomJID: The bare JID of the room.
886 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
887 """
888 d = self._getRoleList(roomJID, "moderator")
889 return d
890
891 def _setAffiliation(self, roomJID, entity, affiliation, reason=None, sender=None):
892 """
893 Send a request to change an entity's affiliation to a MUC room.
894 """
895 request = AdminStanza(recipient=roomJID, sender=sender, stanzaType="set")
896 item = AdminItem(entity=entity, affiliation=affiliation, reason=reason)
897 request.items = [item]
898 return self.request(request)
899
900 def _setRole(self, roomJID, nick, role, reason=None, sender=None):
901 """
902 Send a request to change an occupant's role in a MUC room.
903 """
904 request = AdminStanza(recipient=roomJID, sender=sender, stanzaType="set")
905 item = AdminItem(nick=nick, role=role, reason=reason)
906 request.items = [item]
907 return self.request(request)
908
909 def modifyAffiliationList(self, roomJID, entities, affiliation, sender=None):
910 """
911 Modify an affiliation list.
912
913 @param roomJID: The bare JID of the room.
914 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
915
916 @param entities: The list of entities to change for a room.
917 @type entities: L{list} of
918 L{JID<twisted.words.protocols.jabber.jid.JID>}
919
920 @param affiliation: The affilation to the entities will acquire.
921 @type affiliation: L{str}
922
923 @param sender: The entity sending the request.
924 @type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
925
926 """
927 request = AdminStanza(recipient=roomJID, sender=sender, stanzaType="set")
928 request.items = [
929 AdminItem(entity=entity, affiliation=affiliation) for entity in entities
930 ]
931
932 return self.request(request)
933
934 def grantVoice(self, roomJID, nick, reason=None, sender=None):
935 """
936 Grant voice to an entity.
937
938 @param roomJID: The bare JID of the room.
939 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
940
941 @param nick: The nick name for the user in this room.
942 @type nick: L{str}
943
944 @param reason: The reason for granting voice to the entity.
945 @type reason: L{str}
946
947 @param sender: The entity sending the request.
948 @type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
949 """
950 return self._setRole(
951 roomJID, nick=nick, role="participant", reason=reason, sender=sender
952 )
953
954 def revokeVoice(self, roomJID, nick, reason=None, sender=None):
955 """
956 Revoke voice from a participant.
957
958 This will disallow the entity to send messages to a moderated room.
959
960 @param roomJID: The bare JID of the room.
961 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
962
963 @param nick: The nick name for the user in this room.
964 @type nick: L{str}
965
966 @param reason: The reason for revoking voice from the entity.
967 @type reason: L{str}
968
969 @param sender: The entity sending the request.
970 @type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
971 """
972 return self._setRole(
973 roomJID, nick=nick, role="visitor", reason=reason, sender=sender
974 )
975
976 def grantModerator(self, roomJID, nick, reason=None, sender=None):
977 """
978 Grant moderator privileges to a MUC room.
979
980 @param roomJID: The bare JID of the room.
981 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
982
983 @param nick: The nick name for the user in this room.
984 @type nick: L{str}
985
986 @param reason: The reason for granting moderation to the entity.
987 @type reason: L{str}
988
989 @param sender: The entity sending the request.
990 @type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
991 """
992 return self._setRole(
993 roomJID, nick=nick, role="moderator", reason=reason, sender=sender
994 )
995
996 def ban(self, roomJID, entity, reason=None, sender=None):
997 """
998 Ban a user from a MUC room.
999
1000 @param roomJID: The bare JID of the room.
1001 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
1002
1003 @param entity: The bare JID of the entity to be banned.
1004 @type entity: L{JID<twisted.words.protocols.jabber.jid.JID>}
1005
1006 @param reason: The reason for banning the entity.
1007 @type reason: L{str}
1008
1009 @param sender: The entity sending the request.
1010 @type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
1011 """
1012 return self._setAffiliation(
1013 roomJID, entity, "outcast", reason=reason, sender=sender
1014 )
1015
1016 def kick(self, roomJID, nick, reason=None, sender=None):
1017 """
1018 Kick a user from a MUC room.
1019
1020 @param roomJID: The bare JID of the room.
1021 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
1022
1023 @param nick: The occupant to be banned.
1024 @type nick: L{str}
1025
1026 @param reason: The reason given for the kick.
1027 @type reason: L{str}
1028
1029 @param sender: The entity sending the request.
1030 @type sender: L{JID<twisted.words.protocols.jabber.jid.JID>}
1031 """
1032 return self._setRole(roomJID, nick, "none", reason=reason, sender=sender)
1033
1034 def destroy(self, roomJID, reason=None, alternate=None, password=None):
1035 """
1036 Destroy a room.
1037
1038 @param roomJID: The JID of the room.
1039 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
1040
1041 @param reason: The reason for the destruction of the room.
1042 @type reason: L{str}
1043
1044 @param alternate: The JID of the room suggested as an alternate venue.
1045 @type alternate: L{JID<twisted.words.protocols.jabber.jid.JID>}
1046
1047 """
1048 request = DestructionRequest(
1049 recipient=roomJID, reason=reason, alternate=alternate, password=password
1050 )
1051
1052 return self.request(request)
1053
1054
1055 class User:
1056 """
1057 A user/entity in a multi-user chat room.
1058 """
1059
1060 nick: str
1061 entity: jid.JID | None
1062 affiliation: str | None
1063 role: str | None
1064 status: str | None
1065 show: str | None
1066
1067 def __init__(self, nick: str, entity: jid.JID | None = None) -> None:
1068 self.nick = nick
1069 self.entity = entity
1070 self.affiliation = "none"
1071 self.role = "none"
1072
1073 self.status = None
1074 self.show = None
1075
1076
1077 class Room:
1078 """
1079 A Multi User Chat Room.
1080
1081 An in memory object representing a MUC room from the perspective of
1082 a client.
1083
1084 @ivar roomJID: The Room JID of the MUC room.
1085 @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
1086
1087 @ivar nick: The nick name for the client in this room.
1088 @type nick: L{str}
1089
1090 @ivar occupantJID: The JID of the occupant in the room. Generated from
1091 roomJID and nick.
1092 @type occupantJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
1093
1094 @ivar locked: Flag signalling a locked room. A locked room first needs
1095 to be configured before it can be used. See
1096 L{MUCClientProtocol.getConfiguration} and
1097 L{MUCClientProtocol.configure}.
1098 @type locked: L{bool}
1099 """
1100
1101 locked = False
1102
1103 def __init__(self, roomJID, nick):
1104 """
1105 Initialize the room.
1106 """
1107 self.roomJID = roomJID
1108 self.setNick(nick)
1109 self.roster = {}
1110
1111 def setNick(self, nick):
1112 self.occupantJID = jid.internJID("%s/%s" % (self.roomJID, nick))
1113 self.nick = nick
1114
1115 def addUser(self, user):
1116 """
1117 Add a user to the room roster.
1118
1119 @param user: The user object that is being added to the room.
1120 @type user: L{User}
1121 """
1122 self.roster[user.nick] = user
1123
1124 def inRoster(self, user):
1125 """
1126 Check if a user is in the MUC room.
1127
1128 @param user: The user object to check.
1129 @type user: L{User}
1130 """
1131
1132 return user.nick in self.roster
1133
1134 def getUser(self, nick):
1135 """
1136 Get a user from the room's roster.
1137
1138 @param nick: The nick for the user in the MUC room.
1139 @type nick: L{str}
1140 """
1141 return self.roster.get(nick)
1142
1143 def removeUser(self, user):
1144 """
1145 Remove a user from the MUC room's roster.
1146
1147 @param user: The user object to check.
1148 @type user: L{User}
1149 """
1150 if self.inRoster(user):
1151 del self.roster[user.nick]
1152
1153
1154 @implementer(IMUCClient)
1155 class MUCClient(MUCClientProtocol):
1156 """
1157 Multi-User Chat client protocol.
1158
1159 This is a subclass of L{XMPPHandler} and implements L{IMUCClient}.
1160
1161 @ivar _rooms: Collection of occupied rooms, keyed by the bare JID of the
1162 room. Note that a particular entity can only join a room once
1163 at a time.
1164 """
1165
1166 _rooms: dict[jid.JID, Room]
1167
1168 def __init__(self, reactor: IReactorTime | None = None) -> None:
1169 MUCClientProtocol.__init__(self, reactor)
1170
1171 self._rooms = {}
1172
1173 def _addRoom(self, room: Room) -> None:
1174 """
1175 Add a room to the room collection.
1176
1177 Rooms are stored by the JID of the room itself. I.e. it uses the Room
1178 ID and service parts of the Room JID.
1179
1180 @note: An entity can only join a particular room once.
1181 """
1182 roomJID = room.occupantJID.userhostJID()
1183 self._rooms[roomJID] = room
1184
1185 def _getRoom(self, roomJID: jid.JID) -> Room | None:
1186 """
1187 Grab a room from the room collection.
1188
1189 This uses the Room ID and service parts of the given JID to look up
1190 the L{Room} instance associated with it.
1191 """
1192 return self._rooms.get(roomJID)
1193
1194 def _removeRoom(self, roomJID: jid.JID) -> None:
1195 """
1196 Delete a room from the room collection.
1197 """
1198 if roomJID in self._rooms:
1199 del self._rooms[roomJID]
1200
1201 def _getRoomUser(self, stanza: generic.Stanza) -> tuple[Room | None, User | None]:
1202 """
1203 Lookup the room and user associated with the stanza's sender.
1204 """
1205 occupantJID = stanza.sender
1206
1207 if not occupantJID:
1208 return None, None
1209
1210 # when a user leaves a room we need to update it
1211 room = self._getRoom(occupantJID.userhostJID())
1212 if room is None:
1213 # not in the room yet
1214 return None, None
1215
1216 # Check if user is in roster
1217 nick = occupantJID.resource
1218 user = room.getUser(nick)
1219
1220 return room, user
1221
1222 def unavailableReceived(self, presence: UserPresence) -> None:
1223 """
1224 Unavailable presence was received.
1225
1226 If this was received from a MUC room occupant JID, that occupant has
1227 left the room or changed their nickname.
1228 """
1229
1230 room, user = self._getRoomUser(presence)
1231
1232 if room is None or user is None:
1233 return
1234
1235 room.removeUser(user)
1236
1237 if STATUS_CODE.NEW_NICK in presence.mucStatuses:
1238 # Nickname change: the presence contains the new nick in presence.nick
1239 assert presence.nick is not None
1240 self.userChangedNick(room, user, presence.nick)
1241 else:
1242 self.userLeftRoom(room, user)
1243
1244 def availableReceived(self, presence: UserPresence) -> None:
1245 """
1246 Available presence was received.
1247 """
1248
1249 room, user = self._getRoomUser(presence)
1250
1251 if room is None:
1252 return
1253
1254 if user is None:
1255 assert presence.sender is not None
1256 sender = presence.sender
1257 assert sender.resource is not None
1258 nick = sender.resource
1259 user = User(nick, presence.entity)
1260
1261 # Update user data
1262 user.role = presence.role
1263 user.affiliation = presence.affiliation
1264 user.status = presence.status
1265 user.show = presence.show
1266
1267 if room.inRoster(user):
1268 self.userUpdatedStatus(room, user, presence.show, presence.status)
1269 else:
1270 room.addUser(user)
1271 self.userJoinedRoom(room, user)
1272
1273 def groupChatReceived(self, message: GroupChat) -> None:
1274 """
1275 A group chat message has been received from a MUC room.
1276
1277 There are a few event methods that may get called here.
1278 L{receivedGroupChat}, L{receivedSubject} or L{receivedHistory}.
1279 """
1280 room, user = self._getRoomUser(message)
1281
1282 if room is None:
1283 return
1284
1285 if message.subject is not None:
1286 self.receivedSubject(room, user, message.subject)
1287 elif message.delay is None:
1288 self.receivedGroupChat(room, user, message)
1289 else:
1290 self.receivedHistory(room, user, message)
1291
1292 def userJoinedRoom(self, room: Room, user: User) -> None:
1293 """
1294 User has joined a MUC room.
1295
1296 This method will need to be modified in order for clients to
1297 do something when this event occurs.
1298
1299 @param room: The room the user has joined.
1300
1301 @param user: The user that joined the MUC room.
1302 """
1303 pass
1304
1305 def userLeftRoom(self, room: Room, user: User) -> None:
1306 """
1307 User has left a room.
1308
1309 This method will need to be modified in order for clients to
1310 do something when this event occurs.
1311
1312 @param room: The room the user has joined.
1313
1314 @param user: The user that left the MUC room.
1315 """
1316 pass
1317
1318 def userChangedNick(self, room: Room, user: User, newNick: str) -> None:
1319 """
1320 User has changed their nickname in a room.
1321
1322 This method will need to be modified in order for clients to
1323 do something when this event occurs.
1324
1325 @param room: The room where the nickname change occurred.
1326
1327 @param user: The user that changed their nickname (with old nick).
1328
1329 @param newNick: The new nickname.
1330 """
1331 pass
1332
1333 def userUpdatedStatus(
1334 self, room: Room, user: User, show: str | None, status: str | None
1335 ) -> None:
1336 """
1337 User Presence has been received.
1338
1339 This method will need to be modified in order for clients to
1340 do something when this event occurs.
1341 """
1342 pass
1343
1344 def receivedSubject(self, room: Room, user: User | None, subject: str) -> None:
1345 """
1346 A (new) room subject has been received.
1347
1348 This method will need to be modified in order for clients to
1349 do something when this event occurs.
1350 """
1351 pass
1352
1353 def receivedGroupChat(
1354 self, room: Room, user: User | None, message: GroupChat
1355 ) -> None:
1356 """
1357 A groupchat message was received.
1358
1359 @param room: The room the message was received from.
1360
1361 @param user: The user that sent the message, or L{None} if it was a
1362 message from the room itself.
1363
1364 @param message: The message.
1365 """
1366 pass
1367
1368 def receivedHistory(self, room: Room, user: User | None, message: GroupChat) -> None:
1369 """
1370 A groupchat message from the room's discussion history was received.
1371
1372 This is identical to L{receivedGroupChat}, with the delayed delivery
1373 information (timestamp and original sender) in C{message.delay}. For
1374 anonymous rooms, C{message.delay.sender} is the room's address.
1375
1376 @param room: The room the message was received from.
1377
1378 @param user: The user that sent the message, or L{None} if it was a
1379 message from the room itself.
1380
1381 @param message: The message.
1382 """
1383 pass
1384
1385 def join(
1386 self,
1387 roomJID: jid.JID,
1388 nick: str,
1389 historyOptions: HistoryOptions | None = None,
1390 password: str | None = None,
1391 ) -> defer.Deferred[Room]:
1392 """
1393 Join a MUC room by sending presence to it.
1394
1395 @param roomJID: The JID of the room the entity is joining.
1396
1397 @param nick: The nick name for the entitity joining the room.
1398
1399 @param historyOptions: Options for conversation history sent by the
1400 room upon joining.
1401
1402 @param password: Optional password for the room.
1403
1404 @return: A deferred that fires with the room when the entity is in the
1405 room, or with a failure if an error has occurred.
1406 """
1407
1408 def cb(presence: UserPresence) -> Room:
1409 """
1410 We have presence that says we joined a room.
1411 """
1412 if STATUS_CODE.ROOM_CREATED in presence.mucStatuses:
1413 room.locked = True
1414
1415 return room
1416
1417 def eb(failure: Failure) -> Failure:
1418 self._removeRoom(roomJID)
1419 return failure
1420
1421 room = Room(roomJID, nick)
1422 self._addRoom(room)
1423
1424 d = MUCClientProtocol.join(self, roomJID, nick, historyOptions, password)
1425 d.addCallbacks(cb, eb)
1426 return d
1427
1428 def nick(self, roomJID: jid.JID, nick: str) -> defer.Deferred[Room]:
1429 """
1430 Change an entity's nick name in a MUC room.
1431
1432 See: http://xmpp.org/extensions/xep-0045.html#changenick
1433
1434 @param roomJID: The JID of the room, i.e. without a resource.
1435
1436 @param nick: The new nick name within the room.
1437
1438 @return: A deferred that fires with the room.
1439 """
1440 room = self._getRoom(roomJID)
1441
1442 def cb(presence: UserPresence) -> Room:
1443 # Presence confirmation, change the nickname.
1444 assert room is not None
1445 room.setNick(nick)
1446 return room
1447
1448 d = MUCClientProtocol.nick(self, roomJID, nick)
1449 d.addCallback(cb)
1450 return d
1451
1452 def leave(self, roomJID: jid.JID) -> defer.Deferred[UserPresence]:
1453 """
1454 Leave a MUC room.
1455
1456 See: http://xmpp.org/extensions/xep-0045.html#exit
1457
1458 @param roomJID: The Room JID of the room to leave.
1459 """
1460
1461 def cb(presence: UserPresence) -> UserPresence:
1462 self._removeRoom(roomJID)
1463 return presence
1464
1465 d = MUCClientProtocol.leave(self, roomJID)
1466 d.addCallback(cb)
1467 return d
1468
1469 def status(
1470 self, roomJID: jid.JID, show: str | None = None, status: str | None = None
1471 ) -> defer.Deferred[Room]:
1472 """
1473 Change user status.
1474
1475 See: http://xmpp.org/extensions/xep-0045.html#changepres
1476
1477 @param roomJID: The Room JID of the room.
1478
1479 @param show: The availability of the entity. Common values are xa,
1480 available, etc
1481
1482 @param status: The current status of the entity.
1483 """
1484 room = self._getRoom(roomJID)
1485 d = MUCClientProtocol.status(self, roomJID, show, status)
1486 d.addCallback(lambda _: room)
1487 return d
1488
1489 def destroy(
1490 self,
1491 roomJID: jid.JID,
1492 reason: str | None = None,
1493 alternate: jid.JID | None = None,
1494 password: str | None = None,
1495 ) -> defer.Deferred[generic.Request]:
1496 """
1497 Destroy a room.
1498
1499 @param roomJID: The JID of the room.
1500
1501 @param reason: The reason for the destruction of the room.
1502
1503 @param alternate: The JID of the room suggested as an alternate venue.
1504
1505 @param password: Optional password for the room.
1506 """
1507
1508 def destroyed(iq: domish.Element) -> domish.Element:
1509 self._removeRoom(roomJID)
1510 return iq
1511
1512 d = MUCClientProtocol.destroy(self, roomJID, reason, alternate, password)
1513 d.addCallback(destroyed)
1514 return d