def _load_data(self): _members = set() _admins = set() with open('%s/xsf_roster.txt' % self.data_dir) as roster: for jid in roster: jid = jid.strip() if jid: _members.add(JID(jid)) with open('%s/xsf_admins.txt' % self.data_dir) as admins: for jid in admins: jid = jid.strip() if jid: _admins.add(JID(jid)) self._members = _members self._admins = _admins
def command_roster_vcard(self, arg): if arg: self.command_vcard(arg) return current = self.api.current_tab().selected_row if isinstance(current, Resource): self._get_vcard(JID(current.jid).bare) elif isinstance(current, Contact): self._get_vcard(current.bare_jid)
def _plugins_result(self, iq): jid = JID(iq['from']) if jid.bare != self.room or jid.resource not in self._peers: logging.error("Received plugin list from unknown peer") return peer = self._peers[jid.resource] plugins = iq['plugins'].xml.find("{%s}plugins" % PeerPlugins.namespace) for plugin in plugins: peer.add_plugin(plugin.get('name'), plugin.get('version'))
def get_always(self) -> Set[JID]: results = set() jids = self.xml.findall('{%s}always/{%s}jid' % (self.namespace, self.namespace)) for jid in jids: results.add(JID(jid.text)) return results
def get_never(self): results = set() jids = self.xml.findall('{%s}never/{%s}jid' % ( self.namespace, self.namespace)) for jid in jids: results.add(JID(jid.text)) return results
def command_muc_vcard(self, arg): if not arg: self.core.command.help('vcard') return user = self.api.current_tab().get_user_by_name(arg) if user: # No need to use safeJID here, we already know the JID is valid. jid = JID(self.api.current_tab().name + '/' + user.nick) else: jid = safeJID(arg) self._get_vcard(jid)
def handle_result(form, session): jid = JID(form['values']['jid']) if jid.bare in self._members: self._members.remove(jid) self._save_data() self.xmpp.event('xsf_jid_removed', jid) session['payload'] = None session['next'] = None return session
def check_account(self, jabber_id: str) -> bool: """check if an account exists or not.""" logger.debug(f'check if account {jabber_id} exists or not') api_url = f'{self.root_path}/api/check_account' jid = JID(jabber_id) body = {'user': jid.user, 'host': jid.host} try: return post(api_url, json=body) == 0 except RemoteAPIError: return False
def roster_push_filter(iq): from_ = iq['from'] if from_ and from_ != JID('') and from_ != self.boundjid.bare: reply = iq.reply() reply['type'] = 'error' reply['error']['type'] = 'cancel' reply['error']['code'] = 503 reply['error']['condition'] = 'service-unavailable' reply.send() return self.event('roster_update', iq)
def unregister(self, jabber_id: str) -> bool: """unregister a user.""" logger.debug(f'unregister account {jabber_id}') api_url = f'{self.root_path}/api/unregister' jid = JID(jabber_id) body = {'user': jid.user, 'host': jid.host} try: post(api_url, json=body) return True except RemoteAPIError: return False
def command_vcard(self, arg): if not arg: self.core.command.help('vcard') return try: jid = JID(arg) except InvalidJID: self.api.information('Invalid JID: %s' % arg, 'Error') return self._get_vcard(jid)
def check_room(self, jabber_id: str) -> bool: """check if a room exists or not.""" logger.debug(f'check if room {jabber_id} exists or not') api_url = f'{self.root_path}/api/get_room_options' jid = JID(jabber_id) body = {'name': jid.user, 'service': jid.host} try: props = post(api_url, json=body) return len(props) > 0 except RemoteAPIError: return False
def destroy_room(self, jabber_id: str) -> bool: """destroy a MUC room.""" logger.debug(f'destroy a MUC room by {jabber_id}') api_url = f'{self.root_path}/api/destroy_room' jid = JID(jabber_id) body = {'name': jid.user, 'service': jid.host} try: post(api_url, json=body) return True except RemoteAPIError: return False
def _on_bind_response(self, response): self.xmpp.boundjid = JID(response['bind']['jid']) self.xmpp.bound = True self.xmpp.event('session_bind', self.xmpp.boundjid) self.xmpp.session_bind_event.set() self.xmpp.features.add('bind') log.info("JID set to: %s", self.xmpp.boundjid.full) if 'session' not in self.features['features']: log.debug("Established Session") self.xmpp.sessionstarted = True self.xmpp.event('session_start')
async def _peer_recv_command(self, iq): jid = JID(iq['from']) if jid.bare != self.room or jid.resource not in self._peers: logging.error("Received command from unknown peer") return peer = self._peers[jid.resource] # TODO use plygin interfaces and sub_interfaces plugin_et = iq['command'].xml.find("{%s}plugin" % PeerCommand.namespace) command = iq['command'].xml.find("{%s}command" % PeerCommand.namespace) for plugin in self.plugins: try: distribution = pkg_resources.get_distribution( plugin.__class__.__module__) except pkg_resources.DistributionNotFound: continue if distribution.project_name == plugin_et.get('name') \ and distribution.version == plugin_et.get('version'): msg = {'mucnick': command.get('from'), 'body': command.text} try: result = await self._command(msg, peer) if result is not None: logging.info(f"Command result: {result}") command = iq['command'] reply = iq.reply() et_result = ET.Element('result') et_result.text = result command.xml.append(et_result) reply.set_payload(command.xml) reply.send() else: reply = iq.reply() reply.send() except Exception as e: traceback.print_exc() reply = iq.reply() reply.error() reply['error']['condition'] = "internal-server-error" reply['error']['text'] = str(e) reply.send() return logging.error("Received command for unsupported plugin")
def ping(self, jid=None, ifrom=None, timeout=None): """Send a ping request and calculate RTT. This is a coroutine. Arguments: jid -- The JID that will receive the ping. ifrom -- Specifiy the sender JID. timeout -- Time in seconds to wait for a response. Defaults to self.timeout. """ own_host = False if not jid: if self.xmpp.is_component: jid = self.xmpp.server else: jid = self.xmpp.boundjid.host jid = JID(jid) if jid == self.xmpp.boundjid.host or \ self.xmpp.is_component and jid == self.xmpp.server: own_host = True if not timeout: timeout = self.timeout start = time.time() log.debug('Pinging %s' % jid) try: yield from self.send_ping(jid, ifrom=ifrom, timeout=timeout, coroutine=True) except IqError as e: if own_host: rtt = time.time() - start log.debug('Pinged %s, RTT: %s', jid, rtt) return rtt else: raise e else: rtt = time.time() - start log.debug('Pinged %s, RTT: %s', jid, rtt) return rtt
def ask_confirm(self, jid, id, url, method, *, ifrom=None, message=None): jid = JID(jid) if jid.resource: stanza = self.xmpp.Iq() stanza['type'] = 'get' else: stanza = self.xmpp.Message() stanza['thread'] = uuid4().hex stanza['from'] = ifrom stanza['to'] = jid stanza['confirm']['id'] = id stanza['confirm']['url'] = url stanza['confirm']['method'] = method if not jid.resource: if message is not None: stanza['body'] = message.format(id=id, url=url, method=method) stanza.send() return stanza else: return stanza.send()
def create_room(self, jabber_id: str, host: str = 'localhost', **kwargs) -> bool: """create a MUC room in host with given options.""" logger.debug(f'create a MUC room using {jabber_id}') api_url = f'{self.root_path}/api/create_room_with_opts' jid = JID(jabber_id) options = [{'name': k, 'value': v} for k, v in kwargs.items()] body = { 'name': jid.user, 'service': jid.host, 'host': host, 'options': options } try: post(api_url, json=body) return True except RemoteAPIError: return False
async def ping(self, jid: Optional[JID] = None, ifrom: Optional[JID] = None, timeout: Optional[int] = None) -> float: """Send a ping request and calculate RTT. This is a coroutine. :param jid: The JID that will receive the ping. """ own_host = False if not jid: if self.xmpp.is_component: jid = self.xmpp.server else: jid = self.xmpp.boundjid.host jid = JID(jid) if jid == self.xmpp.boundjid.host or \ self.xmpp.is_component and jid == self.xmpp.server: own_host = True if not timeout: timeout = self.timeout start = time.time() log.debug('Pinging %s' % jid) try: await self.send_ping(jid, ifrom=ifrom, timeout=timeout) except IqError as e: if own_host: rtt = time.time() - start log.debug('Pinged %s, RTT: %s', jid, rtt) return rtt else: raise e else: rtt = time.time() - start log.debug('Pinged %s, RTT: %s', jid, rtt) return rtt
def get_with(self): fields = self.__get_fields() field = fields.get('with') if field: return JID(field['value'])
def get_with(self): return JID(self._get_sub_text('with'))
def get_by(self): return JID(self._get_attr('by'))
def get_source(self): return JID(self._get_attr('source', ''))
def get_jid(self): return JID(self._get_attr('jid', ''))
def authenticate(self): if self.xmpp.authenticated: return False log.debug("Starting jabber:iq:auth Authentication") # Step 1: Request the auth form iq = self.xmpp.Iq() iq['type'] = 'get' iq['to'] = self.xmpp.requested_jid.host iq['auth']['username'] = self.xmpp.requested_jid.user try: resp = iq.send() except IqError as err: log.info("Authentication failed: %s", err.iq['error']['condition']) self.xmpp.event('failed_auth') self.xmpp.disconnect() return True except IqTimeout: log.info("Authentication failed: %s", 'timeout') self.xmpp.event('failed_auth') self.xmpp.disconnect() return True # Step 2: Fill out auth form for either password or digest auth iq = self.xmpp.Iq() iq['type'] = 'set' iq['auth']['username'] = self.xmpp.requested_jid.user # A resource is required, so create a random one if necessary resource = self.xmpp.requested_jid.resource if not resource: resource = str(uuid.uuid4()) iq['auth']['resource'] = resource if 'digest' in resp['auth']['fields']: log.debug('Authenticating via jabber:iq:auth Digest') stream_id = bytes(self.xmpp.stream_id, encoding='utf-8') password = bytes(self.xmpp.password, encoding='utf-8') digest = hashlib.sha1(b'%s%s' % (stream_id, password)).hexdigest() iq['auth']['digest'] = digest else: log.warning('Authenticating via jabber:iq:auth Plain.') iq['auth']['password'] = self.xmpp.password # Step 3: Send credentials try: result = iq.send() except IqError as err: log.info("Authentication failed") self.xmpp.event("failed_auth") self.xmpp.disconnect() except IqTimeout: log.info("Authentication failed") self.xmpp.event("failed_auth") self.xmpp.disconnect() self.xmpp.features.add('auth') self.xmpp.authenticated = True self.xmpp.boundjid = JID(self.xmpp.requested_jid) self.xmpp.boundjid.resource = resource self.xmpp.event('session_bind', self.xmpp.boundjid) log.debug("Established Session") self.xmpp.sessionstarted = True self.xmpp.event('session_start') return True
def get_from(self): from_ = self._get_attr('from') return JID(from_) if from_ else None
def is_member(self, jid): return JID(jid).bare in self._members
def get_with(self) -> Optional[JID]: fields = self.get_fields() field = fields.get('with') if field: return JID(field['value']) return None