def from_xml(self,xmlnode): """Initialize Delay object from an XML node. :Parameters: - `xmlnode`: the jabber:x:delay XML element. :Types: - `xmlnode`: `libxml2.xmlNode`""" if xmlnode.type!="element": raise ValueError,"XML node is not a jabber:x:delay element (not an element)" ns=get_node_ns_uri(xmlnode) if ns and (ns != self.xml_element_namespace or xmlnode.name != self.xml_element_name): raise ValueError,"XML node is not a " + self.xml_element_namespace + " element" stamp=xmlnode.prop("stamp") tm = _parse_ts(stamp) tm=tm[0:8]+(0,) self.timestamp=datetime.datetime.fromtimestamp(time.mktime(tm)) delay_from=from_utf8(xmlnode.prop("from")) if delay_from: try: self.delay_from = JID(delay_from) except JIDError: raise JIDMalformedProtocolError, "Bad JID in the " + self.xml_element_namespace + " 'from' attribute" else: self.delay_from = None self.reason = from_utf8(xmlnode.getContent())
def from_xml(self, xmlnode): """Initialize Delay object from an XML node. :Parameters: - `xmlnode`: the jabber:x:delay XML element. :Types: - `xmlnode`: `libxml2.xmlNode`""" if xmlnode.type != "element": raise ValueError, "XML node is not a jabber:x:delay element (not an element)" ns = get_node_ns_uri(xmlnode) if ns and ns != DELAY_NS or xmlnode.name != "x": raise ValueError, "XML node is not a jabber:x:delay element" stamp = xmlnode.prop("stamp") if stamp.endswith("Z"): stamp = stamp[:-1] if "-" in stamp: stamp = stamp.split("-", 1)[0] try: tm = time.strptime(stamp, "%Y%m%dT%H:%M:%S") except ValueError: raise BadRequestProtocolError, "Bad timestamp" tm = tm[0:8] + (0, ) self.timestamp = datetime.datetime.fromtimestamp(time.mktime(tm)) delay_from = from_utf8(xmlnode.prop("from")) if delay_from: try: self.delay_from = JID(delay_from) except JIDError: raise JIDMalformedProtocolError, "Bad JID in the jabber:x:delay 'from' attribute" else: self.delay_from = None self.reason = from_utf8(xmlnode.getContent())
def from_xml(self, xmlnode): """Initialize Delay object from an XML node. :Parameters: - `xmlnode`: the jabber:x:delay XML element. :Types: - `xmlnode`: `libxml2.xmlNode`""" if xmlnode.type != "element": raise ValueError, "XML node is not a jabber:x:delay element (not an element)" ns = get_node_ns_uri(xmlnode) if ns and ns != DELAY_NS or xmlnode.name != "x": raise ValueError, "XML node is not a jabber:x:delay element" stamp = xmlnode.prop("stamp") if stamp.endswith("Z"): stamp = stamp[:-1] if "-" in stamp: stamp = stamp.split("-", 1)[0] try: tm = time.strptime(stamp, "%Y%m%dT%H:%M:%S") except ValueError: raise BadRequestProtocolError, "Bad timestamp" tm = tm[0:8] + (0,) self.timestamp = datetime.datetime.fromtimestamp(time.mktime(tm)) delay_from = from_utf8(xmlnode.prop("from")) if delay_from: try: self.delay_from = JID(delay_from) except JIDError: raise JIDMalformedProtocolError, "Bad JID in the jabber:x:delay 'from' attribute" else: self.delay_from = None self.reason = from_utf8(xmlnode.getContent())
def _new_from_xml(cls, xmlnode): """Create a new `Field` object from an XML element. :Parameters: - `xmlnode`: the XML element. :Types: - `xmlnode`: `libxml2.xmlNode` :return: the object created. :returntype: `Field` """ field_type = xmlnode.prop("type") label = from_utf8(xmlnode.prop("label")) name = from_utf8(xmlnode.prop("var")) child = xmlnode.children values = [] options = [] required = False desc = None while child: if child.type != "element" or child.ns().content != DATAFORM_NS: pass elif child.name == "required": required = True elif child.name == "desc": desc = from_utf8(child.getContent()) elif child.name == "value": values.append(from_utf8(child.getContent())) elif child.name == "option": options.append(Option._new_from_xml(child)) child = child.next if field_type and not field_type.endswith("-multi") and len(values) > 1: raise BadRequestProtocolError, "Multiple values for a single-value field" return cls(name, values, field_type, label, options, required, desc)
def from_xml(self,node): """Initialize RosterItem from XML node.""" if node.type!="element": raise ValueError,"XML node is not a roster item (not en element)" ns=get_node_ns_uri(node) if ns and ns!=ROSTER_NS or node.name!="item": raise ValueError,"XML node is not a roster item" jid=JID(node.prop("jid").decode("utf-8")) subscription=node.prop("subscription") if subscription not in ("none","from","to","both","remove"): subscription="none" ask=node.prop("ask") if ask not in ("subscribe",None): ask=None name=from_utf8(node.prop("name")) groups=[] n=node.children while n: if n.type!="element": n=n.next continue ns=get_node_ns_uri(n) if ns and ns!=ROSTER_NS or n.name!="group": n=n.next continue group=n.getContent() if group: groups.append(from_utf8(group)) n=n.next self.jid=jid self.name=name self.groups=groups self.subscription=subscription self.ask=ask
def __from_xml(self, xmlnode): """Initialize `Register` from an XML node. :Parameters: - `xmlnode`: the jabber:x:register XML element. :Types: - `xmlnode`: `libxml2.xmlNode`""" self.__logger.debug("Converting jabber:iq:register element from XML") if xmlnode.type != "element": raise ValueError, "XML node is not a jabber:iq:register element (not an element)" ns = get_node_ns_uri(xmlnode) if ns and ns != REGISTER_NS or xmlnode.name != "query": raise ValueError, "XML node is not a jabber:iq:register element" for element in xml_element_iter(xmlnode.children): ns = get_node_ns_uri(element) if ns == DATAFORM_NS and element.name == "x" and not self.form: self.form = Form(element) elif ns != REGISTER_NS: continue name = element.name if name == "instructions" and not self.instructions: self.instructions = from_utf8(element.getContent()) elif name == "registered": self.registered = True elif name == "remove": self.remove = True elif name in legacy_fields and not getattr(self, name): value = from_utf8(element.getContent()) if value is None: value = u"" self.__logger.debug(u"Setting legacy field %r to %r" % (name, value)) setattr(self, name, value)
def response(self,response): """Process a client reponse. :Parameters: - `response`: the response from the client. :Types: - `response`: `str` :return: a challenge, a success indicator or a failure indicator. :returntype: `sasl.Challenge`, `sasl.Success` or `sasl.Failure`""" s=response.split("\000") if len(s)!=3: self.__logger.debug("Bad response: %r" % (response,)) return Failure("not-authorized") authzid,username,password=s authzid=from_utf8(authzid) username=from_utf8(username) password=from_utf8(password) if not self.password_manager.check_password(username,password): self.__logger.debug("Bad password. Response was: %r" % (response,)) return Failure("not-authorized") info={"mechanism":"PLAIN","username":username} if self.password_manager.check_authzid(authzid,info): return Success(username,None,authzid) else: self.__logger.debug("Authzid verification failed.") return Failure("invalid-authzid")
def _new_from_xml(cls, xmlnode): """Create a new `Field` object from an XML element. :Parameters: - `xmlnode`: the XML element. :Types: - `xmlnode`: `libxml2.xmlNode` :return: the object created. :returntype: `Field` """ field_type = xmlnode.prop("type") label = from_utf8(xmlnode.prop("label")) name = from_utf8(xmlnode.prop("var")) child = xmlnode.children values = [] options = [] required = False desc = None while child: if child.type != "element" or child.ns().content != DATAFORM_NS: pass elif child.name == "required": required = True elif child.name == "desc": desc = from_utf8(child.getContent()) elif child.name == "value": values.append(from_utf8(child.getContent())) elif child.name == "option": options.append(Option._new_from_xml(child)) child = child.next if field_type and not field_type.endswith( "-multi") and len(values) > 1: raise BadRequestProtocolError, "Multiple values for a single-value field" return cls(name, values, field_type, label, options, required, desc)
def from_xml(self, node): """Initialize RosterItem from XML node.""" if node.type != "element": raise ValueError, "XML node is not a roster item (not en element)" ns = get_node_ns_uri(node) if ns and ns != ROSTER_NS or node.name != "item": raise ValueError, "XML node is not a roster item" jid = JID(node.prop("jid").decode("utf-8")) subscription = node.prop("subscription") if subscription not in ("none", "from", "to", "both", "remove"): subscription = "none" ask = node.prop("ask") if ask not in ("subscribe", None): ask = None name = from_utf8(node.prop("name")) groups = [] n = node.children while n: if n.type != "element": n = n.next continue ns = get_node_ns_uri(n) if ns and ns != ROSTER_NS or n.name != "group": n = n.next continue group = n.getContent() if group: groups.append(from_utf8(group)) n = n.next self.jid = jid self.name = name self.groups = groups self.subscription = subscription self.ask = ask
def handle_message(self, stanza): ''' <message from='[email protected]/desktop' to='*****@*****.**'> <x xmlns='jabber:x:conference' jid='*****@*****.**' password='******' reason='Hey Hecate, this is the place for all good witches!'/> </message> ''' try: fromjid = stanza.get_from() x = stanza.xpath_eval('c:x', {'c': CONFERENCE_NS})[0] roomjid = JID(from_utf8(x.prop('jid'))) roomname = JID(roomjid).node password = x.prop('password') password = from_utf8(password) if password else None reason = x.prop('reason') reason = from_utf8(reason) if reason else None except Exception: traceback.print_exc() return False else: if not all((roomname, fromjid)): return False self.protocol.hub.on_invite( protocol=self.protocol, buddy=fromjid, room_name=roomname, message=reason, on_yes=lambda: self.protocol.join_chat_jid( roomjid, self.protocol.self_buddy.jid.node)) return True # don't let other message handlers do it
def from_xml(self, xmlnode): """Initialize Delay object from an XML node. :Parameters: - `xmlnode`: the jabber:x:delay XML element. :Types: - `xmlnode`: `libxml2.xmlNode`""" if xmlnode.type != "element": raise ValueError, "XML node is not a jabber:x:delay element (not an element)" ns = get_node_ns_uri(xmlnode) if ns and (ns != self.xml_element_namespace or xmlnode.name != self.xml_element_name): raise ValueError, "XML node is not a " + self.xml_element_namespace + " element" stamp = xmlnode.prop("stamp") tm = _parse_ts(stamp) tm = tm[0:8] + (0, ) self.timestamp = datetime.datetime.fromtimestamp(time.mktime(tm)) delay_from = from_utf8(xmlnode.prop("from")) if delay_from: try: self.delay_from = JID(delay_from) except JIDError: raise JIDMalformedProtocolError, "Bad JID in the " + self.xml_element_namespace + " 'from' attribute" else: self.delay_from = None self.reason = from_utf8(xmlnode.getContent())
def handle_message(self, stanza): ''' <message from='[email protected]/desktop' to='*****@*****.**'> <x xmlns='jabber:x:conference' jid='*****@*****.**' password='******' reason='Hey Hecate, this is the place for all good witches!'/> </message> ''' try: fromjid = stanza.get_from() x = stanza.xpath_eval('c:x',{'c':CONFERENCE_NS})[0] roomjid = JID(from_utf8(x.prop('jid'))) roomname = JID(roomjid).node password = x.prop('password') password = from_utf8(password) if password else None reason = x.prop('reason') reason = from_utf8(reason) if reason else None except Exception: traceback.print_exc() return False else: if not all((roomname, fromjid)): return False self.protocol.hub.on_invite( protocol = self.protocol, buddy = fromjid, room_name = roomname, message = reason, on_yes = lambda: self.protocol.join_chat_jid(roomjid, self.protocol.self_buddy.jid.node)) return True # don't let other message handlers do it
def __from_xml(self, xmlnode): """Initialize a `Form` object from an XML element. :Parameters: - `xmlnode`: the XML element. :Types: - `xmlnode`: `libxml2.xmlNode` """ self.fields = [] self.reported_fields = [] self.items = [] self.title = None self.instructions = None if (xmlnode.type != "element" or xmlnode.name != "x" or xmlnode.ns().content != DATAFORM_NS): raise ValueError, "Not a form: " + xmlnode.serialize() self.type = xmlnode.prop("type") if not self.type in self.allowed_types: raise BadRequestProtocolError, "Bad form type: %r" % (self.type,) child = xmlnode.children while child: if child.type != "element" or child.ns().content != DATAFORM_NS: pass elif child.name == "title": self.title = from_utf8(child.getContent()) elif child.name == "instructions": self.instructions = from_utf8(child.getContent()) elif child.name == "field": self.fields.append(Field._new_from_xml(child)) elif child.name == "item": self.items.append(Item._new_from_xml(child)) elif child.name == "reported": self.__get_reported(child) child = child.next
def __from_xml(self, node): if node.type!="element": raise ValueError,"XML node is not a %s element (not en element)" % self.xml_element_name ns=get_node_ns_uri(node) if ns and ns!=self.xml_element_namespace or node.name!=self.xml_element_name: raise ValueError,"XML node is not an %s element" % self.xml_element_name labelss = xpath_eval(node, 'g:labels',{'g':GOOGLE_MAIL_NOTIFY_NS}) labels = labelss[0].getContent() if labelss else None self.labels = from_utf8(labels).split('|') if labels else [] senderss = xpath_eval(node, 'g:senders',{'g':GOOGLE_MAIL_NOTIFY_NS}) self.senders = Senders(senderss[0]) if senderss else [] subjects = xpath_eval(node, 'g:subject',{'g':GOOGLE_MAIL_NOTIFY_NS}) self.subject = from_utf8(subjects[0].getContent()) if subjects else None snippets = xpath_eval(node, 'g:snippet',{'g':GOOGLE_MAIL_NOTIFY_NS}) self.snippet = from_utf8(snippets[0].getContent()) if snippets else None self.tid = int(from_utf8(node.prop("tid"))) self.participation = int(from_utf8(node.prop("participation"))) self.messages = int(from_utf8(node.prop("messages"))) self.date = int(from_utf8(node.prop("date"))) self.url = from_utf8(node.prop("date"))
def received_data(self, stanza) : from_jid = stanza.get_from() iq = stanza.get_query() sid = from_utf8(iq.prop('sid')) data = base64.b64decode(iq.getContent()) seq = from_utf8(iq.prop('seq')) print "get data seq : ", seq session = self.session_mgr.get_session(from_jid, sid) if session : session.received_data(data, seq) iq = stanza.make_result_response() else : iq = stanza.make_error_response('unexpected-request') self.client.get_stream().send(iq)
def __from_xml(self, node): '''A libxml2 node to a digsby.action''' if node.type!="element": raise ValueError,"XML node is not an action element (not en element)" ns = get_node_ns_uri(node) if ns and ns != DIGSBY_STATS_COUNTER_NS or node.name != "action": raise ValueError,"XML node is not an action element" type = node.prop("type") self.type = from_utf8(type) if type is not None else None initial = node.prop("initial") self.initial = int(from_utf8(initial)) if initial is not None else None value = node.prop("value") self.value = int(from_utf8(value)) if value is not None else None result = node.prop("result") self.result = int(from_utf8(result)) if result is not None else None
def __from_xml(self, node): if node.type != "element": raise ValueError, "XML node is not a %s element (not en element)" % self.xml_element_name ns = get_node_ns_uri(node) if ns and ns != self.xml_element_namespace or node.name != self.xml_element_name: raise ValueError, "XML node is not an %s element" % self.xml_element_name self.name = from_utf8(node.prop("name")) self.address = from_utf8(node.prop("address")) originator = node.prop("originator") self.originator = int(from_utf8(originator)) if originator else 0 unread = node.prop("unread") self.unread = int(from_utf8(unread)) if unread else 0
def __from_xml(self,node): if node.type!="element": raise ValueError,"XML node is not a %s element (not en element)" % self.xml_element_name ns=get_node_ns_uri(node) if ns and ns!=self.xml_element_namespace or node.name!=self.xml_element_name: raise ValueError,"XML node is not an %s element" % self.xml_element_name self.name = from_utf8(node.prop("name")) self.address = from_utf8(node.prop("address")) originator = node.prop("originator") self.originator = int(from_utf8(originator)) if originator else 0 unread = node.prop("unread") self.unread = int(from_utf8(unread)) if unread else 0
def __disco_items(self,iq): """Handle a disco#items request. `self.disco_get_items` method will be used to prepare the query response. :Parameters: - `iq`: the IQ stanza received. :Types: - `iq`: `pyxmpp.iq.Iq`""" q=iq.get_query() if q.hasProp("node"): node=from_utf8(q.prop("node")) else: node=None items=self.disco_get_items(node,iq) if isinstance(items,DiscoItems): resp=iq.make_result_response() self.__logger.debug("Disco-items query: %s preparing response: %s with reply: %s" % (iq.serialize(),resp.serialize(),items.xmlnode.serialize())) resp.set_content(items.xmlnode.copyNode(1)) elif isinstance(items,Stanza): resp=items else: resp=iq.make_error_response("item-not-found") self.__logger.debug("Disco-items response: %s" % (resp.serialize(),)) self.stream.send(resp)
def __disco_items(self, iq): """Handle a disco#items request. `self.disco_get_items` method will be used to prepare the query response. :Parameters: - `iq`: the IQ stanza received. :Types: - `iq`: `pyxmpp.iq.Iq`""" q = iq.get_query() if q.hasProp("node"): node = from_utf8(q.prop("node")) else: node = None items = self.disco_get_items(node, iq) if isinstance(items, DiscoItems): resp = iq.make_result_response() self.__logger.debug( "Disco-items query: %s preparing response: %s with reply: %s" % (iq.serialize(), resp.serialize(), items.xmlnode.serialize())) resp.set_content(items.xmlnode.copyNode(1)) elif isinstance(items, Stanza): resp = items else: resp = iq.make_error_response("item-not-found") self.__logger.debug("Disco-items response: %s" % (resp.serialize(), )) self.stream.send(resp)
def __disco_info(self,iq): """Handle a disco-info query. :Parameters: - `iq`: the stanza received. Types: - `iq`: `pyxmpp.Iq`""" q=iq.get_query() if q.hasProp("node"): node=from_utf8(q.prop("node")) else: node=None info=self.disco_get_info(node,iq) if isinstance(info,DiscoInfo): resp=iq.make_result_response() self.__logger.debug("Disco-info query: %s preparing response: %s with reply: %s" % (iq.serialize(),resp.serialize(),info.xmlnode.serialize())) resp.set_content(info.xmlnode.copyNode(1)) elif isinstance(info,Stanza): resp=info else: resp=iq.make_error_response("item-not-found") self.__logger.debug("Disco-info response: %s" % (resp.serialize(),)) self.stream.send(resp)
def __from_xml(self, node): if node.type!="element": raise ValueError,"XML node is not a %s element (not en element)" % self.xml_element_name ns=get_node_ns_uri(node) if ns and ns!=self.xml_element_namespace or node.name!=self.xml_element_name: raise ValueError,"XML node is not an %s element" % self.xml_element_name self.result_time = int(from_utf8(node.prop("result-time"))) self.total_matched = int(from_utf8(node.prop("total-matched"))) self.url = from_utf8(node.prop("url")) total_estimate = node.prop("messages") self.total_estimate = int(from_utf8(total_estimate)) if total_estimate else 0 threads = xpath_eval(node, 'g:mail-thread-info',{'g':GOOGLE_MAIL_NOTIFY_NS}) self.extend(MailThreadInfo(thread) for thread in threads)
def _plain_auth_in_stage2(self, username, _unused, stanza): """Handle the second stage (<iq type='set'/>) of legacy "plain" authentication. [server only]""" password=stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"}) if password: password=from_utf8(password[0].getContent()) if not password: self.__logger.debug("No password found in plain auth request") iq=stanza.make_error_response("bad-request") self.send(iq) return if self.check_password(username,password): iq=stanza.make_result_response() self.send(iq) self.peer_authenticated=True self.auth_method_used="plain" self.state_change("authorized",self.peer) self._post_auth() else: self.__logger.debug("Plain auth failed") iq=stanza.make_error_response("bad-request") e=iq.get_error() e.add_custom_condition('jabber:iq:auth:error',"user-unauthorized") self.send(iq)
def from_xml(self,node): if node.type!="element": raise ValueError,"XML node is not a ip (not en element)" ns=get_node_ns_uri(node) if ns and ns!=self.xml_element_namespace or node.name!=self.xml_element_name: raise ValueError,"XML node is not a %s descriptor" % self.xml_element_name self.ip = from_utf8(node.getContent())
def _plain_auth_in_stage2(self, username, _unused, stanza): """Handle the second stage (<iq type='set'/>) of legacy "plain" authentication. [server only]""" password = stanza.xpath_eval("a:query/a:password", {"a": "jabber:iq:auth"}) if password: password = from_utf8(password[0].getContent()) if not password: self.__logger.debug("No password found in plain auth request") iq = stanza.make_error_response("bad-request") self.send(iq) return if self.check_password(username, password): iq = stanza.make_result_response() self.send(iq) self.peer_authenticated = True self.auth_method_used = "plain" self.state_change("authorized", self.peer) self._post_auth() else: self.__logger.debug("Plain auth failed") iq = stanza.make_error_response("bad-request") e = iq.get_error() e.add_custom_condition('jabber:iq:auth:error', "user-unauthorized") self.send(iq)
def from_xml(self, node): if node.type != "element": raise ValueError, "XML node is not a ip (not en element)" ns = get_node_ns_uri(node) if ns and ns != self.xml_element_namespace or node.name != self.xml_element_name: raise ValueError, "XML node is not a %s descriptor" % self.xml_element_name self.ip = from_utf8(node.getContent())
def auth_in_stage2(self, stanza): """Handle the second stage (<iq type='set'/>) of legacy ("plain" or "digest") authentication. [server only]""" self.lock.acquire() try: if "plain" not in self.auth_methods and "digest" not in self.auth_methods: iq = stanza.make_error_response("not-allowed") self.send(iq) return username = stanza.xpath_eval("a:query/a:username", {"a": "jabber:iq:auth"}) if username: username = from_utf8(username[0].getContent()) resource = stanza.xpath_eval("a:query/a:resource", {"a": "jabber:iq:auth"}) if resource: resource = from_utf8(resource[0].getContent()) if not username or not resource: self.__logger.debug( "No username or resource found in auth request") iq = stanza.make_error_response("bad-request") self.send(iq) return if stanza.xpath_eval("a:query/a:password", {"a": "jabber:iq:auth"}): if "plain" not in self.auth_methods: iq = stanza.make_error_response("not-allowed") self.send(iq) return else: return self._plain_auth_in_stage2(username, resource, stanza) if stanza.xpath_eval("a:query/a:digest", {"a": "jabber:iq:auth"}): if "plain" not in self.auth_methods: iq = stanza.make_error_response("not-allowed") self.send(iq) return else: return self._digest_auth_in_stage2(username, resource, stanza) finally: self.lock.release()
def get_type(self): """Get the error type. :return: type of the error. :returntype: `unicode`""" if not self.xmlnode.hasProp("type"): self.upgrade() return from_utf8(self.xmlnode.prop("type"))
def get_type(self): """Get "type" attribute of the stanza. :return: value of the "type" attribute (stanza type) or None. :returntype: `unicode`""" if self.xmlnode.hasProp("type"): return from_utf8(self.xmlnode.prop("type")) else: return None
def get_id(self): """Get "id" attribute of the stanza. :return: value of the "id" attribute (stanza identifier) or None. :returntype: `unicode`""" if self.xmlnode.hasProp("id"): return from_utf8(self.xmlnode.prop("id")) else: return None
def get_password(self): """Get password from the MUC request. :returntype: `unicode` """ for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "password": return from_utf8(child.getContent()) return None
def get_history(self): """Return history parameters carried by the stanza. :returntype: `HistoryParameters`""" for child in xml_element_iter(self.xmlnode.children): if get_node_ns_uri(child) == MUC_NS and child.name == "history": maxchars = from_utf8(child.prop("maxchars")) if maxchars is not None: maxchars = int(maxchars) maxstanzas = from_utf8(child.prop("maxstanzas")) if maxstanzas is not None: maxstanzas = int(maxstanzas) maxseconds = from_utf8(child.prop("maxseconds")) if maxseconds is not None: maxseconds = int(maxseconds) # TODO: since -- requires parsing of Jabber dateTime profile since = None return HistoryParameters(maxchars, maxstanzas, maxseconds, since)
def get_show(self): """Get presence "show" field. :return: value of stanza's <show/> field. :returntype: `unicode`""" n = self.xpath_eval("ns:show") if n: return from_utf8(n[0].getContent()) else: return None
def get_status(self): """Get presence status description. :return: value of stanza's <status/> field. :returntype: `unicode`""" n = self.xpath_eval("ns:status") if n: return from_utf8(n[0].getContent()) else: return None
def get_subject(self): """Get the message subject. :return: the message subject or `None` if there is no subject. :returntype: `unicode`""" n = self.xpath_eval("ns:subject") if n: return from_utf8(n[0].getContent()) else: return None
def from_xml(self, node, strict=True): """ Initialize Roster object from XML node. If `strict` is False, than invalid items in the XML will be ignored. """ node_ = node.prop("node") sid = node.prop("sid") self.sid = from_utf8(sid) if sid else None mode = node.prop("mode") self.mode = from_utf8(mode) if mode else None self.mode = self.mode if self.mode != 'tcp' else None if node_: self.node = node_.decode("utf-8") else: self.node = None if node.type != "element": raise ValueError, "XML node is not a bytestreams (not en element)" ns = get_node_ns_uri(node) if ns and ns != BYTESTREAMS_NS or node.name != "query": raise ValueError, "XML node is not a bytestreams query" n = node.children while n: if n.type != "element": n = n.next continue ns = get_node_ns_uri(n) if ns and ns != BYTESTREAMS_NS: n = n.next continue if n.name == "streamhost": try: self.add_host(n) except ValueError: if strict: raise elif n.name == "streamhost-used": host_used = JID(n.prop("jid").decode("utf-8")) self.host_used = host_used elif n.name == "activate": activate = JID(n.getContent()) self.activate = activate n = n.next
def get_body(self): """Get the body of the message. :return: the body of the message or `None` if there is no body. :returntype: `unicode`""" n = self.xpath_eval("ns:body") if n: return from_utf8(n[0].getContent()) else: return None
def get_body(self): """Get the body of the message. :return: the body of the message or `None` if there is no body. :returntype: `unicode`""" n=self.xpath_eval("ns:body") if n: return from_utf8(n[0].getContent()) else: return None
def get_thread(self): """Get the thread-id subject. :return: the thread-id or `None` if there is no thread-id. :returntype: `unicode`""" n=self.xpath_eval("ns:thread") if n: return from_utf8(n[0].getContent()) else: return None
def received_close_request(self, stanza) : from_jid = stanza.get_from() sid = from_utf8(stanza.get_query().prop('sid')) session = self.session_mgr.get_session(from_jid, sid) if session : session.received_close() iq = stanza.make_result_response() else : iq = stanza.make_error_response('unexpected-request') self.client.get_stream().send(iq)
def get_thread(self): """Get the thread-id subject. :return: the thread-id or `None` if there is no thread-id. :returntype: `unicode`""" n = self.xpath_eval("ns:thread") if n: return from_utf8(n[0].getContent()) else: return None
def get_status(self): """Get presence status description. :return: value of stanza's <status/> field. :returntype: `unicode`""" n=self.xpath_eval("ns:status") if n: return from_utf8(n[0].getContent()) else: return None
def get_show(self): """Get presence "show" field. :return: value of stanza's <show/> field. :returntype: `unicode`""" n=self.xpath_eval("ns:show") if n: return from_utf8(n[0].getContent()) else: return None
def from_xml(self,node,strict=True): """ Initialize Roster object from XML node. If `strict` is False, than invalid items in the XML will be ignored. """ node_=node.prop("node") sid=node.prop("sid") self.sid = from_utf8(sid) if sid else None mode=node.prop("mode") self.mode = from_utf8(mode) if mode else None self.mode = self.mode if self.mode != 'tcp' else None if node_: self.node = node_.decode("utf-8") else: self.node = None if node.type!="element": raise ValueError,"XML node is not a bytestreams (not en element)" ns=get_node_ns_uri(node) if ns and ns!=BYTESTREAMS_NS or node.name!="query": raise ValueError,"XML node is not a bytestreams query" n=node.children while n: if n.type!="element": n=n.next continue ns=get_node_ns_uri(n) if ns and ns!=BYTESTREAMS_NS: n=n.next continue if n.name=="streamhost": try: self.add_host(n) except ValueError: if strict: raise elif n.name=="streamhost-used": host_used=JID(n.prop("jid").decode("utf-8")) self.host_used=host_used elif n.name=="activate": activate=JID(n.getContent()) self.activate=activate n=n.next
def get_event(self): """Get the message event :return: the message event or `None` if there is no event :returntype: `unicode`""" n=self.xpath_eval("ns:event") if n: return from_utf8(n[0].getContent()) else: return None
def __init__(self, xmlnode_or_cond, ns=None, copy=True, parent=None): """Initialize an ErrorNode object. :Parameters: - `xmlnode_or_cond`: XML node to be wrapped into this object or error condition name. - `ns`: XML namespace URI of the error condition element (to be used when the provided node has no namespace). - `copy`: When `True` then the XML node will be copied, otherwise it is only borrowed. - `parent`: Parent node for the XML node to be copied or created. :Types: - `xmlnode_or_cond`: `libxml2.xmlNode` or `unicode` - `ns`: `unicode` - `copy`: `bool` - `parent`: `libxml2.xmlNode`""" if type(xmlnode_or_cond) is str: xmlnode_or_cond = unicode(xmlnode_or_cond, "utf-8") self.xmlnode = None self.borrowed = 0 if isinstance(xmlnode_or_cond, libxml2.xmlNode): self.__from_xml(xmlnode_or_cond, ns, copy, parent) elif isinstance(xmlnode_or_cond, ErrorNode): if not copy: raise TypeError, "ErrorNodes may only be copied" self.ns = from_utf8(xmlnode_or_cond.ns.getContent()) self.xmlnode = xmlnode_or_cond.xmlnode.docCopyNode(common_doc, 1) if not parent: parent = common_root parent.addChild(self.xmlnode) elif ns is None: raise ValueError, "Condition namespace not given" else: if parent: self.xmlnode = parent.newChild(common_ns, "error", None) self.borrowed = 1 else: self.xmlnode = common_root.newChild(common_ns, "error", None) cond = self.xmlnode.newChild(None, to_utf8(xmlnode_or_cond), None) ns = cond.newNs(ns, None) cond.setNs(ns) self.ns = from_utf8(ns.getContent())
def __init__(self,xmlnode_or_cond,ns=None,copy=True,parent=None): """Initialize an ErrorNode object. :Parameters: - `xmlnode_or_cond`: XML node to be wrapped into this object or error condition name. - `ns`: XML namespace URI of the error condition element (to be used when the provided node has no namespace). - `copy`: When `True` then the XML node will be copied, otherwise it is only borrowed. - `parent`: Parent node for the XML node to be copied or created. :Types: - `xmlnode_or_cond`: `libxml2.xmlNode` or `unicode` - `ns`: `unicode` - `copy`: `bool` - `parent`: `libxml2.xmlNode`""" if type(xmlnode_or_cond) is str: xmlnode_or_cond=unicode(xmlnode_or_cond,"utf-8") self.xmlnode=None self.borrowed=0 if isinstance(xmlnode_or_cond,libxml2.xmlNode): self.__from_xml(xmlnode_or_cond,ns,copy,parent) elif isinstance(xmlnode_or_cond,ErrorNode): if not copy: raise TypeError, "ErrorNodes may only be copied" self.ns=from_utf8(xmlnode_or_cond.ns.getContent()) self.xmlnode=xmlnode_or_cond.xmlnode.docCopyNode(common_doc,1) if not parent: parent=common_root parent.addChild(self.xmlnode) elif ns is None: raise ValueError, "Condition namespace not given" else: if parent: self.xmlnode=parent.newChild(common_ns,"error",None) self.borrowed=1 else: self.xmlnode=common_root.newChild(common_ns,"error",None) cond=self.xmlnode.newChild(None,to_utf8(xmlnode_or_cond),None) ns=cond.newNs(ns,None) cond.setNs(ns) self.ns=from_utf8(ns.getContent())
def get_text(self): """Get the description text from the error element. :return: the text provided with the error or `None`. :returntype: `unicode`""" c = self.xpath_eval("ns:*") if not c: self.upgrade() t = self.xpath_eval("ns:text") if not t: return None return from_utf8(t[0].getContent())