This repository has been archived by the owner on Jan 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
service.py
2081 lines (1657 loc) · 70.5 KB
/
service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
########################################################################
# File name: service.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
import asyncio
import functools
import uuid
from datetime import datetime, timedelta
from enum import Enum
import aioxmpp.callbacks
import aioxmpp.forms
import aioxmpp.service
import aioxmpp.stanza
import aioxmpp.structs
import aioxmpp.tracking
import aioxmpp.im.conversation
import aioxmpp.im.dispatcher
import aioxmpp.im.p2p
import aioxmpp.im.service
from . import xso as muc_xso
def _extract_one_pair(body):
"""
Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking.
"""
if not body:
return None, None
try:
return None, body[None]
except KeyError:
return min(body.items(), key=lambda x: x[0])
class LeaveMode(Enum):
"""
The different reasons for a user to leave or be removed from MUC.
.. attribute:: DISCONNECTED
The local client disconnected. This only occurs in events referring to
the local entity.
.. attribute:: SYSTEM_SHUTDOWN
The remote server shut down.
.. attribute:: NORMAL
The leave was initiated by the occupant themselves and was not a kick or
ban.
.. attribute:: KICKED
The user was kicked from the room.
.. attribute:: AFFILIATION_CHANGE
Changes in the affiliation of the user caused them to be removed.
.. attribute:: MODERATION_CHANGE
Changes in the moderation settings of the room caused the user to be
removed.
.. attribute:: BANNED
The user was banned from the room.
.. attribute:: ERROR
The user was removed due to an error when communicating with the client
or the users server.
Not all servers support this. If not supported by the server, one will
typically see a :attr:`KICKED` status code with an appropriate
:attr:`~.Presence.status` message.
.. versionadded:: 0.10
"""
DISCONNECTED = -2
SYSTEM_SHUTDOWN = -1
NORMAL = 0
KICKED = 1
AFFILIATION_CHANGE = 3
MODERATION_CHANGE = 4
BANNED = 5
ERROR = 6
class _OccupantDiffClass(Enum):
UNIMPORTANT = 0
NICK_CHANGED = 1
LEFT = 2
class Occupant(aioxmpp.im.conversation.AbstractConversationMember):
"""
A tracking object to track a single occupant in a :class:`Room`.
.. seealso::
:class:`~.AbstractConversationMember`
for additional notes on some of the pre-defined attributes.
.. autoattribute:: direct_jid
.. autoattribute:: conversation_jid
.. autoattribute:: uid
.. autoattribute:: nick
.. attribute:: presence_state
The :class:`~.PresenceState` of the occupant.
.. attribute:: presence_status
The :class:`~.LanguageMap` holding the presence status text of the
occupant.
.. attribute:: affiliation
The affiliation of the occupant with the room. This may be :data:`None`
with faulty MUC implementations.
.. attribute:: role
The current role of the occupant within the room. This may be
:data:`None` with faulty MUC implementations.
"""
def __init__(self,
occupantjid,
is_self,
presence_state=aioxmpp.structs.PresenceState(available=True),
presence_status={},
affiliation=None,
role=None,
jid=None):
super().__init__(occupantjid, is_self)
self.presence_state = presence_state
self.presence_status = aioxmpp.structs.LanguageMap(presence_status)
self.affiliation = affiliation
self.role = role
self._direct_jid = jid
if jid is None:
self._uid = b"urn:uuid:" + uuid.uuid4().bytes
else:
self._set_uid_from_direct_jid(self._direct_jid)
def _set_uid_from_direct_jid(self, jid):
self._uid = b"xmpp:" + str(jid.bare()).encode("utf-8")
@property
def direct_jid(self):
"""
The real :class:`~aioxmpp.JID` of the occupant.
If the MUC is anonymous and we do not have the permission to see the
real JIDs of occupants, this is :data:`None`.
"""
return self._direct_jid
@property
def nick(self):
"""
The nickname of the occupant.
"""
return self.conversation_jid.resource
@property
def uid(self):
"""
This is either a random identifier if the real JID of the occupant is
not known, or an identifier derived from the real JID of the occupant.
Note that as per the semantics of the :attr:`uid`, users **must** treat
it as opaque.
.. seealso::
:class:`~aioxmpp.im.conversation.AbstractConversationMember.uid`
Documentation of the attribute on the base class, with
additional information on semantics.
"""
return self._uid
@classmethod
def from_presence(cls, presence, is_self):
try:
item = presence.xep0045_muc_user.items[0]
except (AttributeError, IndexError):
affiliation = None
if presence.type_ == aioxmpp.structs.PresenceType.UNAVAILABLE:
role = "none" # unavailable must be the "none" role
else:
role = None
jid = None
else:
affiliation = item.affiliation
role = item.role
jid = item.jid
return cls(
occupantjid=presence.from_,
is_self=is_self,
presence_state=aioxmpp.structs.PresenceState.from_stanza(presence),
presence_status=aioxmpp.structs.LanguageMap(presence.status),
affiliation=affiliation,
role=role,
jid=jid,
)
def update(self, other):
if self.conversation_jid != other.conversation_jid:
raise ValueError("occupant JID mismatch")
self.presence_state = other.presence_state
self.presence_status.clear()
self.presence_status.update(other.presence_status)
self.affiliation = other.affiliation or self.affiliation
self.role = other.role or self.role
if self._direct_jid is None and other.direct_jid is not None:
self._set_uid_from_direct_jid(other.direct_jid)
self._direct_jid = other.direct_jid or self._direct_jid
def __repr__(self):
return "<{}.{} occupantjid={!r} uid={!r} jid={!r}>".format(
type(self).__module__,
type(self).__qualname__,
self._conversation_jid,
self._uid,
self._direct_jid,
)
class RoomState(Enum):
"""
Enumeration which describes the state a :class:`~.muc.Room` is in.
.. attribute:: JOIN_PRESENCE
The room is in the process of being joined and the presence state
transfer is going on.
.. attribute:: HISTORY
Presence state transfer has happened, but the room subject has not
been received yet. This is where history replay messages are
received.
When entering this state, :attr:`~.muc.Room.muc_active` becomes true.
.. attribute:: ACTIVE
The join has completed, including history replay and receiving the
subject.
.. attribute:: DISCONNECTED
The MUC is suspended or disconnected. If the MUC is disconnected,
:attr:`~.muc.Room.muc_joined` will be false, too.
"""
JOIN_PRESENCE = 0
HISTORY = 1
ACTIVE = 2
DISCONNECTED = 3
class Room(aioxmpp.im.conversation.AbstractConversation):
"""
:term:`Conversation` representing a single :xep:`45` Multi-User Chat.
.. note::
This is an implementation of :class:`~.AbstractConversation`. The
members which do not carry the ``muc_`` prefix usually have more
extensive documentation there. This documentation here only provides
a short synopsis for those members plus the changes with respect to
the base interface.
.. versionchanged:: 0.9
In 0.9, the :class:`Room` interface was re-designed to match
:class:`~.AbstractConversation`.
The following properties are provided:
.. autoattribute:: features
.. autoattribute:: jid
.. autoattribute:: me
.. autoattribute:: members
These properties are specific to MUC:
.. autoattribute:: muc_active
.. autoattribute:: muc_joined
.. autoattribute:: muc_state
.. autoattribute:: muc_subject
.. autoattribute:: muc_subject_setter
.. attribute:: muc_autorejoin
A boolean flag indicating whether this MUC is supposed to be
automatically rejoined when the stream it is used gets destroyed and
re-estabished.
.. attribute:: muc_password
The password to use when (re-)joining. If :attr:`autorejoin` is
:data:`None`, this can be cleared after :meth:`on_enter` has been
emitted.
The following methods and properties provide interaction with the MUC
itself:
.. automethod:: ban
.. automethod:: kick
.. automethod:: leave
.. automethod:: send_message
.. automethod:: send_message_tracked
.. automethod:: set_nick
.. automethod:: set_topic
.. automethod:: muc_request_voice
.. automethod:: muc_set_role
.. automethod:: muc_set_affiliation
The interface provides signals for most of the rooms events. The following
keyword arguments are used at several signal handlers (which is also noted
at their respective documentation):
`muc_actor` = :data:`None`
The :class:`~.xso.UserActor` instance of the corresponding
:class:`~.xso.UserExt`, describing which other occupant caused the
event.
Note that the `muc_actor` is in fact not a :class:`~.Occupant`.
`muc_reason` = :data:`None`
The reason text in the corresponding :class:`~.xso.UserExt`, which
gives more information on why an action was triggered.
.. note::
Signal handlers attached to any of the signals below **must** accept
arbitrary keyword arguments for forward compatibility. For details see
the documentation on :class:`~.AbstractConversation`.
.. signal:: on_enter(**kwargs)
Emits when the initial room :class:`~.Presence` stanza for the
local JID is received. This means that the join to the room is complete;
the message history and subject are not transferred yet though.
.. seealso::
:meth:`on_muc_enter`
is an extended version of this signal which contains additional
MUC-specific information.
.. versionchanged:: 0.10
The :meth:`on_enter` signal does not receive any arguments anymore
to make MUC comply with the :class:`AbstractConversation` spec.
.. signal:: on_muc_enter(presence, occupant, *, muc_status_codes=set(), **kwargs)
This is an extended version of :meth:`on_enter` which adds MUC-specific
arguments.
:param presence: The initial presence stanza.
:param occupant: The :class:`Occupant` which will be used to track the
local user.
:param muc_status_codes: The set of status codes received in the
initial join.
:type muc_status_codes: :class:`~.abc.Set` of :class:`int` or
:class:`~.StatusCode`
.. versionadded:: 0.10
.. signal:: on_message(msg, member, source, **kwargs)
A message occured in the conversation.
:param msg: Message which was received.
:type msg: :class:`aioxmpp.Message`
:param member: The member object of the sender.
:type member: :class:`.Occupant`
:param source: How the message was acquired
:type source: :class:`~.MessageSource`
The notable specialities about MUCs compared to the base specification
at :meth:`.AbstractConversation.on_message` are:
* Carbons do not happen for MUC messages.
* MUC Private Messages are not handled here; see :class:`MUCClient` for
MUC PM details.
* MUCs reflect messages; to make this as easy to handle as possible,
reflected messages are **not** emitted via the :meth:`on_message`
event **if and only if** they were sent with tracking (see
:meth:`send_message_tracked`) and they were detected as reflection.
See :meth:`send_message_tracked` for details and caveats on the
tracking implementation.
When **history replay** happens, since joins and leaves are not part of
the history, it is not always possible to reason about the identity of
the sender of a history message. To avoid possible spoofing attacks,
the following caveats apply to the :class:`~.Occupant` objects handed
as `member` during history replay:
* Two identical :class:`~.Occupant` objects are only used *iff* the
nickname *and* the actual address of the entity are equal. This
implies that unless this client has the permission to see JIDs of
occupants of the MUC, all :class:`~.Occupant` objects during history
replay will be different instances.
* If the nickname and the actual address of a message from history
match, the current :class:`~.Occupant` object for the respective
occupant is used.
* :class:`~.Occupant` objects which are created for history replay are
never part of :attr:`members`. They are only used to convey the
information passed in the messages from the history replay, which
would otherwise be inaccessible.
.. seealso::
:meth:`.AbstractConversation.on_message` for the full
specification.
.. signal:: on_presence_changed(member, resource, presence, **kwargs)
The presence state of an occupant has changed.
:param member: The member object of the affected member.
:type member: :class:`Occupant`
:param resource: The resource of the member which changed presence.
:type resource: :class:`str` or :data:`None`
:param presence: The presence stanza
:type presence: :class:`aioxmpp.Presence`
`resource` is always :data:`None` for MUCs and unavailable presence
implies that the occupant left the room. In this case, only
:meth:`on_leave` is emitted.
.. seealso::
:meth:`.AbstractConversation.on_presence_changed` for the full
specification.
.. signal:: on_nick_changed(member, old_nick, new_nick, *, muc_status_codes=set(), **kwargs)
The nickname of an occupant has changed
:param member: The occupant whose nick has changed.
:type member: :class:`Occupant`
:param old_nick: The old nickname of the member.
:type old_nick: :class:`str` or :data:`None`
:param new_nick: The new nickname of the member.
:type new_nick: :class:`str`
:param muc_status_codes: The set of status codes received in the leave
notification.
:type muc_status_codes: :class:`~.abc.Set` of :class:`int` or
:class:`~.StatusCode`
The new nickname is already set in the `member` object. Both `old_nick`
and `new_nick` are not :data:`None`.
.. seealso::
:meth:`.AbstractConversation.on_nick_changed` for the full
specification.
.. versionchanged:: 0.10
The `muc_status_codes` argument was added.
.. signal:: on_topic_changed(member, new_topic, *, muc_nick=None, **kwargs)
The topic of the conversation has changed.
:param member: The member object who changed the topic.
:type member: :class:`Occupant` or :data:`None`
:param new_topic: The new topic of the conversation.
:type new_topic: :class:`.LanguageMap`
:param muc_nick: The nickname of the occupant who changed the topic.
:type muc_nick: :class:`str`
The `member` is matched by nickname. It is possible that the member is
not in the room at the time the topic chagne is received (for example
on a join).
`muc_nick` is always the nickname of the entity who changed the topic.
If the entity is currently not joined or has changed nick since the
topic was set, `member` will be :data:`None`, but `muc_nick` is still
the nickname of the actor.
.. note::
:meth:`on_topic_changed` is emitted during join, iff a topic is set
in the MUC.
.. signal:: on_join(member, **kwargs)
A new occupant has joined the MUC.
:param member: The member object of the new member.
:type member: :class:`Occupant`
When this signal is called, the `member` is already included in the
:attr:`members`.
.. signal:: on_leave(member, *, muc_leave_mode=None, muc_actor=None, muc_reason=None, **kwargs)
An occupant has left the conversation.
:param member: The member object of the previous occupant.
:type member: :class:`Occupant`
:param muc_leave_mode: The cause of the removal.
:type muc_leave_mode: :class:`LeaveMode` member
:param muc_actor: The actor object if available.
:type muc_actor: :class:`~.xso.UserActor`
:param muc_reason: The reason for the cause, as given by the actor.
:type muc_reason: :class:`str`
:param muc_status_codes: The set of status codes received in the leave
notification.
:type muc_status_codes: :class:`~.abc.Set` of :class:`int` or
:class:`~.StatusCode`
When this signal is called, the `member` has already been removed from
the :attr:`members`.
.. versionchanged:: 0.10
The `muc_status_codes` argument was added.
.. signal:: on_muc_suspend()
Emits when the stream used by this MUC gets destroyed (see
:meth:`~.node.Client.on_stream_destroyed`) and the MUC is configured to
automatically rejoin the user when the stream is re-established.
.. signal:: on_muc_resume()
Emits when the MUC is about to be rejoined on a new stream. This can be
used by implementations to clear their MUC state, as it is emitted
*before* any events like presence are emitted.
The internal state of :class:`Room` is cleared before :meth:`on_resume`
is emitted, which implies that presence events will be emitted for all
occupants on re-join, independent on their presence before the
connection was lost.
Note that on a rejoin, all presence is re-emitted.
.. signal:: on_muc_role_request(form, submission_future)
Emits when an unprivileged occupant requests a role change and the
MUC service wants this occupant to approve or deny it.
:param form: The approval form as presented by the service.
:type form: :class:`~.VoiceRequestForm`
:param submission_future: A future to which the form to submit must
be sent.
:type submission_future: :class:`asyncio.Future`
To decide on a role change request, a handler of this signal must
fill in the form and set the form as a result of the
`submission_future`.
Once the result is set, the reply is sent by the MUC service
automatically.
It is required for signal handlers to check whether the
`submission_future` is already done before processing the form (as it
is possible that multiple handlers are connected to this signal).
.. signal:: on_exit(*, muc_leave_mode=None, muc_actor=None, muc_reason=None, muc_status_codes=set(), **kwargs)
Emits when the unavailable :class:`~.Presence` stanza for the
local JID is received.
:param muc_leave_mode: The cause of the removal.
:type muc_leave_mode: :class:`LeaveMode` member
:param muc_actor: The actor object if available.
:type muc_actor: :class:`~.xso.UserActor`
:param muc_reason: The reason for the cause, as given by the actor.
:type muc_reason: :class:`str`
:param muc_status_codes: The set of status codes received in the leave
notification.
:type muc_status_codes: :class:`~.abc.Set` of :class:`int` or
:class:`~.StatusCode`
.. note::
The keyword arguments `muc_actor`, `muc_reason` and
`muc_status_codes` are not always given. Be sure to default them
accordingly.
.. versionchanged:: 0.10
The `muc_status_codes` argument was added.
The following signals inform users about state changes related to **other**
occupants in the chat room. Note that different events may fire for the
same presence stanza. A common example is a ban, which triggers
:meth:`on_affiliation_change` (as the occupants affiliation is set to
``"outcast"``) and then :meth:`on_leave` (with :attr:`LeaveMode.BANNED`
`mode`).
.. signal:: on_muc_affiliation_changed(member, *, actor=None, reason=None, status_codes=set(), **kwargs)
Emits when the affiliation of a `member` with the room changes.
:param occupant: The member of the room.
:type occupant: :class:`Occupant`
:param actor: The actor object if available.
:type actor: :class:`~.xso.UserActor`
:param reason: The reason for the change, as given by the actor.
:type reason: :class:`str`
:param status_codes: The set of status codes received in the change
notification.
:type status_codes: :class:`~.abc.Set` of :class:`int` or
:class:`~.StatusCode`
`occupant` is the :class:`Occupant` instance tracking the occupant whose
affiliation changed.
.. versionchanged:: 0.10
The `status_codes` argument was added.
.. signal:: on_muc_role_changed(member, *, actor=None, reason=None, status_codes=set(), , **kwargs)
Emits when the role of an `occupant` in the room changes.
:param occupant: The member of the room.
:type occupant: :class:`Occupant`
:param actor: The actor object if available.
:type actor: :class:`~.xso.UserActor`
:param reason: The reason for the change, as given by the actor.
:type reason: :class:`str`
:param status_codes: The set of status codes received in the change
notification.
:type status_codes: :class:`~.abc.Set` of :class:`int` or
:class:`~.StatusCode`
`occupant` is the :class:`Occupant` instance tracking the occupant whose
role changed.
.. versionchanged:: 0.10
The `status_codes` argument was added.
"""
# this occupant state events
on_muc_suspend = aioxmpp.callbacks.Signal()
on_muc_resume = aioxmpp.callbacks.Signal()
on_muc_enter = aioxmpp.callbacks.Signal()
# other occupant state events
on_muc_affiliation_changed = aioxmpp.callbacks.Signal()
on_muc_role_changed = aioxmpp.callbacks.Signal()
# approval requests
on_muc_role_request = aioxmpp.callbacks.Signal()
def __init__(self, service, mucjid):
super().__init__(service)
self._mucjid = mucjid
self._occupant_info = {}
self._subject = aioxmpp.structs.LanguageMap()
self._subject_setter = None
self._joined = False
self._active = False
self._this_occupant = None
self._tracking_by_id = {}
self._tracking_metadata = {}
self._tracking_by_body = {}
self._state = RoomState.JOIN_PRESENCE
self._history_replay_occupants = {}
self.muc_autorejoin = False
self.muc_password = None
@property
def service(self):
return self._service
@property
def muc_state(self):
"""
The state the MUC is in. This is one of the
:class:`~.muc.RoomState` enumeration values. See there for
documentation on the meaning.
This state is more detailed than :attr:`muc_active`.
"""
return self._state
@property
def muc_active(self):
"""
A boolean attribute indicating whether the connection to the MUC is
currently live.
This becomes true when :attr:`joined` first becomes true. It becomes
false whenever the connection to the MUC is interrupted in a way which
requires re-joining the MUC (this implies that if stream management is
being used, active does not become false on temporary connection
interruptions).
"""
return self._active
@property
def muc_joined(self):
"""
This attribute becomes true when :meth:`on_enter` is first emitted and
stays true until :meth:`on_exit` is emitted.
When it becomes false, the :class:`Room` is removed from the
bookkeeping of the :class:`.MUCClient` to which it belongs and is thus
dead.
"""
return self._joined
@property
def muc_subject(self):
"""
The current subject of the MUC, as :class:`~.structs.LanguageMap`.
"""
return self._subject
@property
def muc_subject_setter(self):
"""
The nick name of the entity who set the subject.
"""
return self._subject_setter
@property
def me(self):
"""
A :class:`Occupant` instance which tracks the local user. This is
:data:`None` until :meth:`on_enter` is emitted; it is never set to
:data:`None` again, but the identity of the object changes on each
:meth:`on_enter`.
"""
return self._this_occupant
@property
def jid(self):
"""
The (bare) :class:`aioxmpp.JID` of the MUC which this :class:`Room`
tracks.
"""
return self._mucjid
@property
def members(self):
"""
A copy of the list of occupants. The local user is always the first
item in the list, unless the :meth:`on_enter` has not fired yet.
"""
if self._this_occupant is not None:
items = [self._this_occupant]
else:
items = []
items += list(self._occupant_info.values())
return items
@property
def features(self):
"""
The set of features supported by this MUC. This may vary depending on
features exported by the MUC service, so be sure to check this for each
individual MUC.
"""
return {
aioxmpp.im.conversation.ConversationFeature.BAN,
aioxmpp.im.conversation.ConversationFeature.BAN_WITH_KICK,
aioxmpp.im.conversation.ConversationFeature.KICK,
aioxmpp.im.conversation.ConversationFeature.SEND_MESSAGE,
aioxmpp.im.conversation.ConversationFeature.SEND_MESSAGE_TRACKED,
aioxmpp.im.conversation.ConversationFeature.SET_TOPIC,
aioxmpp.im.conversation.ConversationFeature.SET_NICK,
}
def _enter_active_state(self):
self._state = RoomState.ACTIVE
self._history_replay_occupants.clear()
def _suspend(self):
self.on_muc_suspend()
self._active = False
self._state = RoomState.DISCONNECTED
self._history_replay_occupants.clear()
def _disconnect(self):
if not self._joined:
return
self.on_exit(
muc_leave_mode=LeaveMode.DISCONNECTED
)
self._joined = False
self._active = False
self._state = RoomState.DISCONNECTED
self._history_replay_occupants.clear()
def _resume(self):
self._this_occupant = None
self._occupant_info = {}
self._active = False
self._state = RoomState.JOIN_PRESENCE
self.on_muc_resume()
def _match_tracker(self, message):
try:
tracker = self._tracking_by_id[message.id_]
except KeyError:
if (self._this_occupant is not None and
message.from_ == self._this_occupant.conversation_jid):
key = _extract_one_pair(message.body)
self._service.logger.debug("trying to match by body: %r",
key)
try:
trackers = self._tracking_by_body[key]
except KeyError:
alt_key = (None, key[1])
try:
trackers = self._tracking_by_body[alt_key]
except KeyError:
trackers = None
else:
self._service.logger.debug("found tracker by body")
else:
self._service.logger.debug(
"can’t match by body because of sender mismatch"
)
trackers = None
if not trackers:
tracker = None
else:
tracker = trackers[0]
else:
self._service.logger.debug("found tracker by ID")
if tracker is None:
return False
id_key, body_key = self._tracking_metadata.pop(tracker)
del self._tracking_by_id[id_key]
# remove tracker from list and delete list map entry if empty
trackers = self._tracking_by_body[body_key]
del trackers[0]
if not trackers:
del self._tracking_by_body[body_key]
try:
tracker._set_state(
aioxmpp.tracking.MessageState.DELIVERED_TO_RECIPIENT,
message,
)
except ValueError:
# this can happen if another implementation was faster with
# changing the state than we were.
pass
return True
def _handle_message(self, message, peer, sent, source):
self._service.logger.debug("%s: inbound message %r",
self._mucjid,
message)
if self._state == RoomState.HISTORY and not message.xep0203_delay:
# WORKAROUND: prosody#1053; AFFECTS: <= 0.9.12, <= 0.10
self._service.logger.debug(
"%s: received un-delayed message during history replay: "
"assuming that server is buggy and replay is over.",
self._mucjid,
)
self._enter_active_state()
if not sent:
if self._match_tracker(message):
return
if (self._this_occupant and
self._this_occupant._conversation_jid == message.from_):
occupant = self._this_occupant
else:
occupant = self._occupant_info.get(message.from_, None)
if self._state == RoomState.HISTORY and not sent:
if (message.xep0045_muc_user and
message.xep0045_muc_user.items):
item = message.xep0045_muc_user.items[0]
jid = item.jid or None
affiliation = item.affiliation or None
role = item.role or None
else:
jid = None
affiliation = None
role = None
occupant = self._history_replay_occupants.get(jid, occupant)
if (not occupant or
occupant.direct_jid is None or
occupant.direct_jid != jid):
occupant = Occupant(message.from_, False,
presence_state=aioxmpp.PresenceState(),
jid=jid,
affiliation=affiliation,
role=role)
if jid is not None:
self._history_replay_occupants[jid] = occupant
elif occupant is None:
occupant = Occupant(message.from_, False,
presence_state=aioxmpp.PresenceState())
if not message.body and message.subject:
self._subject = aioxmpp.structs.LanguageMap(message.subject)
self._subject_setter = message.from_.resource
self.on_topic_changed(
occupant,
self._subject,
muc_nick=message.from_.resource,
)
self._enter_active_state()
elif message.body:
if occupant is not None and occupant == self._this_occupant:
tracker = aioxmpp.tracking.MessageTracker()
tracker._set_state(
aioxmpp.tracking.MessageState.DELIVERED_TO_RECIPIENT
)
tracker.close()
else:
tracker = None
self.on_message(
message,
occupant,
source,
tracker=tracker,
)
def _diff_presence(self, stanza, info, existing):
if (not info.presence_state.available and
muc_xso.StatusCode.NICKNAME_CHANGE in
stanza.xep0045_muc_user.status_codes):
return (