def testDomainWithTrailingDot(self): domain = 'example.com.' jid1 = JID(domain=domain) jid2 = JID('user@%s/resource' % domain) self.assertEqual(jid1.domain, 'example.com') self.assertEqual(jid2.domain, 'example.com')
def __init__(self, nickname, sender_nick, sender_jid, user_jid,\ message_text, message_html, is_pm, room_member_list): self.nickname = nickname self.sender_nick = sender_nick self.sender_jid = JID(sender_jid) self.user_jid = JID(user_jid) self.message_text = message_text self.message_html = message_html self.is_pm = is_pm self.room_member_list = room_member_list if self._is_command(nickname, message_text) or is_pm: self.command, self.args = self._get_command_and_args(message_text) self.nick_reason = self._get_nick_reason(self.args) else: self.command, self.args, self.nick_reason = None, None, None self.is_ping = self._is_ping(nickname, message_text) or is_pm log.debug('''creating message: self: {} sender: {} jid {} user {} message: {} message_html: {} parsed: {}|{} is_ping: {}'''.format(self.nickname, self.sender_nick, self.sender_jid, self.user_jid, self.message_text, self.message_html, self.command, self.args, self.is_ping)) log.debug('room list: %r', self.room_member_list) log.info('{}: {}'.format(self.sender_nick, self.message_text))
def testDomainInvalidIPv6MissingBracket(self): domain = '[::1' jid1 = JID(domain=domain) jid2 = JID('user@%s/resource' % domain) self.assertEqual(jid1.domain, '[::1]') self.assertEqual(jid2.domain, '[::1]')
def testACEDomain(self): domain = 'xn--bcher-kva.ch' jid1 = JID(domain=domain) jid2 = JID('user@%s/resource' % domain) self.assertEqual(jid1.domain.encode('utf-8'), b'b\xc3\xbccher.ch') self.assertEqual(jid2.domain.encode('utf-8'), b'b\xc3\xbccher.ch')
def testJIDUnescape(self): jid = JID(local='here\'s_a_wild_&_/cr%zy/_address_for:<wv>("IMPS")', domain='example.com') ujid = jid.unescape() self.assertEqual(ujid.local, 'here\'s_a_wild_&_/cr%zy/_address_for:<wv>("IMPS")') jid = JID(local='blah\\foo\\20bar', domain='example.com') ujid = jid.unescape() self.assertEqual(ujid.local, 'blah\\foo\\20bar')
def nickname_to_jid(self, room, nick): # type: (str, str) -> JID jid = self.plugin['xep_0045'].getJidProperty(room, nick, "jid") if (jid is None or jid == ''): return JID(local=nick.replace(' ', ''), domain=self.boundjid.domain) else: return jid
def join_muc(self, room): # type: (str) -> None if room in self.rooms: return logging.debug("Joining " + room) self.rooms.add(room) muc_jid = JID(local=room, domain=options.conference_domain) xep0045 = self.plugin['xep_0045'] try: xep0045.joinMUC(muc_jid, self.nick, wait=True) except InvalidJID: logging.error("Could not join room: " + str(muc_jid)) return # Configure the room. Really, we should only do this if the room is # newly created. form = None try: form = xep0045.getRoomConfig(muc_jid) except ValueError: pass if form: xep0045.configureRoom(muc_jid, form) else: logging.error("Could not configure room: " + str(muc_jid))
def testJIDEscape(self): jid = JID(local='here\'s_a_wild_&_/cr%zy/_address_for:<wv>("IMPS")', domain='example.com') self.assertEqual( jid.local, r'here\27s_a_wild_\26_\2fcr%zy\2f_address_for\3a\3cwv\3e(\22IMPS\22)' )
def zulip_to_jid(email: str, jabber_domain: str) -> JID: jid = JID(email, domain=jabber_domain) if (options.zulip_email_suffix and options.zulip_email_suffix in jid.username and not jid.username.endswith("-bot")): jid.username = jid.username.rpartition(options.zulip_email_suffix)[0] return jid
def testJIDaliases(self): """Test changing JID using aliases for domain.""" j = JID('user@someserver/resource') j.server = 'anotherserver' self.check_jid(j, domain='anotherserver') j.host = 'yetanother' self.check_jid(j, domain='yetanother')
def nickname_to_jid(self, room: str, nick: str) -> JID: jid = self.plugin["xep_0045"].getJidProperty(room, nick, "jid") if jid is None or jid == "": return JID(local=nick.replace(" ", ""), domain=self.boundjid.domain) else: return jid
def testtransport_presence_event_handler_with_exception(self): """ Test to check the presence method with an exception raised of the signal class. """ sig_dict, signal = self.setup_vars_mocks() transport = XmppTransport.factory( "1", sig_dict["Signal"]["Overlays"]["A0FB389"], signal, signal._presence_publisher, None, None) presence = { "from": "raj", "to": "raj@ipop", "status": "uid?#1234434323" } transport.boundjid = JID("raj@ipop/ipop") transport.send_msg = MagicMock() transport.send_msg.side_effect = Exception() jid_cache = Mock() presence_publisher = Mock() transport._presence_publisher = presence_publisher transport._presence_publisher.post_update = MagicMock() transport._jid_cache = jid_cache transport._jid_cache.add_entry = MagicMock() transport._sig.sig_log = MagicMock() transport.presence_event_handler(presence) transport.send_msg.assert_called_once() transport._sig.sig_log.assert_called_once() print("Passed : testtransport_presence_event_handler_with_uid")
def seen(self, message): '''[nick/jid] Report when a user was last seen''' # TODO: I'm not totally convinced about the logic around jidtarget/ # other if statements below. args = message.args jidtarget = JID(self.bot.get_jid_from_nick(args)).bare target = jidtarget or args seen = self.store.get('seen:' + target) spoke = self.store.get('spoke:' + target) now = datetime.now() if jidtarget and self.bot.jid_is_in_room(jidtarget) and spoke: spoke = spoke.decode('utf-8').strip() spokedate = datetime.strptime(spoke, self.date_format) ago = self.get_time_ago(now, spokedate) return '{} last seen speaking at {} ({})'.format(args, spoke, ago) elif seen: seen = seen.decode('utf-8').strip() seendate = datetime.strptime(seen, self.date_format) ago = self.get_time_ago(now, seendate) return '{} last seen in room at {} ({})'.format(args, seen, ago) else: return "No records found for user '{}'".format(args)
def leave_muc(self, room: str) -> None: if room not in self.rooms: return logging.debug("Leaving " + room) self.rooms.remove(room) muc_jid = JID(local=room, domain=options.conference_domain) self.plugin['xep_0045'].leaveMUC(muc_jid, self.nick)
def testJIDSetFullWithUser(self): """Test setting the full JID with a user portion.""" j = JID('user@domain/resource') j.full = 'otheruser@otherdomain/otherresource' self.check_jid(j, 'otheruser', 'otherdomain', 'otherresource', 'otheruser@otherdomain', 'otheruser@otherdomain/otherresource', 'otheruser@otherdomain/otherresource')
def testJIDBareUser(self): """Test setting the bare JID with a user.""" j = JID('user@domain/resource') j.bare = 'otheruser@otherdomain' self.check_jid(j, 'otheruser', 'otherdomain', 'resource', 'otheruser@otherdomain', 'otheruser@otherdomain/resource', 'otheruser@otherdomain/resource')
def wyzepal_to_jid(email, jabber_domain): # type: (str, str) -> JID jid = JID(email, domain=jabber_domain) if (options.wyzepal_email_suffix and options.wyzepal_email_suffix in jid.username and not jid.username.endswith("-bot")): jid.username = jid.username.rpartition(options.wyzepal_email_suffix)[0] return jid
def real_jid(self): """ The JID of the room occupant, they used to login. Will only work if the errbot is moderator in the MUC or it is not anonymous. """ room_jid = self._node + '@' + self._domain jid = JID( self._room.xep0045.getJidProperty(room_jid, self.resource, 'jid')) return jid.bare
def testJIDFullNoUserNoResource(self): """ Test setting the full JID without a user portion and without a resource. """ j = JID('user@domain/resource') j.full = 'otherdomain' self.check_jid(j, '', 'otherdomain', '', 'otherdomain', 'otherdomain', 'otherdomain')
def testJIDchange(self): """Test changing JID of the form 'user@server/resource/with/slashes'""" j = JID('user1@someserver1/some1/resource1') j.user = '******' j.domain = 'someserver' j.resource = 'some/resource' self.check_jid(j, 'user', 'someserver', 'some/resource', 'user@someserver', 'user@someserver/some/resource', 'user@someserver/some/resource')
def testJIDNoUser(self): """Test JID of the form 'component.domain.tld'.""" self.check_jid(JID('component.someserver'), '', 'component.someserver', '', 'component.someserver', 'component.someserver', 'component.someserver')
def testJIDFromFull(self): """Test using JID of the form 'user@server/resource/with/slashes'.""" self.check_jid(JID('user@someserver/some/resource'), 'user', 'someserver', 'some/resource', 'user@someserver', 'user@someserver/some/resource', 'user@someserver/some/resource')
def testJIDNoResource(self): """Test using JID of the form 'user@domain'.""" self.check_jid(JID('user@someserver'), 'user', 'someserver', '', 'user@someserver', 'user@someserver', 'user@someserver')
def stream_message(self, msg: Dict[str, str]) -> None: assert self.jabber is not None stream = msg["display_recipient"] if not stream.endswith("/xmpp"): return room = stream_to_room(stream) jabber_recipient = JID(local=room, domain=options.conference_domain) outgoing = self.jabber.make_message(mto=jabber_recipient, mbody=msg["content"], mtype="groupchat") outgoing["thread"] = "\u1FFFE" outgoing.send()
def stream_message(self, msg): # type: (Dict[str, str]) -> None stream = msg['display_recipient'] if not stream.endswith("/xmpp"): return room = stream_to_room(stream) jabber_recipient = JID(local=room, domain=options.conference_domain) outgoing = self.jabber.make_message(mto=jabber_recipient, mbody=msg['content'], mtype='groupchat') outgoing['thread'] = u'\u1FFFE' outgoing.send()
def get_vcard(self, jid=None, ifrom=None, local=None, cached=False, block=True, callback=None, timeout=None): if local is None: if jid is not None and not isinstance(jid, JID): jid = JID(jid) if self.xmpp.is_component: if jid.domain == self.xmpp.boundjid.domain: local = True else: if str(jid) == str(self.xmpp.boundjid): local = True jid = jid.full elif jid in (None, ''): local = True if local: vcard = self.api['get_vcard'](jid, None, ifrom) if not isinstance(vcard, Iq): iq = self.xmpp.Iq() if vcard is None: vcard = VCardTemp() iq.append(vcard) return iq return vcard if cached: vcard = self.api['get_vcard'](jid, None, ifrom) if vcard is not None: if not isinstance(vcard, Iq): iq = self.xmpp.Iq() iq.append(vcard) return iq return vcard iq = self.xmpp.Iq() iq['to'] = jid iq['from'] = ifrom iq['type'] = 'get' iq.enable('vcard_temp') vcard = iq.send(block=block, callback=callback, timeout=timeout) if block: self.api['set_vcard'](vcard['from'], args=vcard['vcard_temp']) return vcard
def create_rooms(self, rooms, callback=None): """ Creates or joins the given rooms :param rooms: A list of rooms to join / create :param callback: Method to call back when all rooms have been created :raise ValueError: No Multi-User Chat service available """ # Look for the MUC service if necessary if not self.__muc_service: try: self.__muc_service = next(self.iter_services(FEATURE_MUC)) except StopIteration: raise ValueError("No Multi-User Chat service on server") if callback is not None: # Prepare a callback self.__countdowns.add( _MarksCallback((JID(local=room, domain=self.__muc_service) for room in rooms), callback)) # Prepare the room creator creator = RoomCreator(self, "Herald-XMPP-RoomCreator") # Prepare rooms configuration rooms_config = { # ... no max users limit 'muc#roomconfig_maxusers': '0', # ... accepted members only 'muc#roomconfig_membersonly': '1', # ... every participant can send invites 'muc#roomconfig_allowinvites': '1', # ... room can disappear 'muc#roomconfig_persistentroom': '0', # ... OpenFire: Forbid nick changes 'x-muc#roomconfig_canchangenick': '0' } # Create rooms for room in rooms: creator.create_room(room, self.__muc_service, self._nick, rooms_config, self.__room_created, self.__room_error)
def testDomainIPv6(self): domain = '[::1]' jid1 = JID(domain=domain) jid2 = JID('user@%s/resource' % domain)
if options.mode not in ('public', 'personal'): config_error( "Bad value for --mode: must be one of 'public' or 'personal'") if None in (options.jid, options.jabber_password): config_error( "You must specify your Jabber JID and Jabber password either " "in the Zulip configuration file or on the commandline") zulipToJabber = ZulipToJabberBot( zulip.init_from_options(options, "JabberMirror/" + __version__)) # This won't work for open realms that don't have a consistent domain options.zulip_domain = zulipToJabber.client.email.partition('@')[-1] try: jid = JID(options.jid) except InvalidJID as e: config_error("Bad JID: %s: %s" % (options.jid, e.message)) if options.conference_domain is None: options.conference_domain = "conference.%s" % (jid.domain, ) xmpp = JabberToZulipBot(jid, options.jabber_password, get_rooms(zulipToJabber)) address = None if options.jabber_server_address: address = (options.jabber_server_address, options.jabber_server_port) if not xmpp.connect(use_tls=not options.no_use_tls, address=address): sys.exit("Unable to connect to Jabber server")
def testJIDEscapeExistingSequences(self): jid = JID(local='blah\\foo\\20bar', domain='example.com') self.assertEqual(jid.local, 'blah\\foo\\5c20bar')