def componentConnected(self, xmlstream): LogEvent(INFO) self.xmlstream = xmlstream self.xmlstream.addObserver("/iq", self.iq.onIq) self.xmlstream.addObserver("/presence", self.onPresence) self.xmlstream.addObserver("/message", self.onMessage) self.xmlstream.addObserver("/bind", self.onBind) self.xmlstream.addObserver("/route", self.onRouteMessage) self.xmlstream.addObserver( "/error[@xmlns='http://etherx.jabber.org/streams']", self.streamError) if config.useXCP and config.compjid: pres = Element((None, "presence")) pres.attributes["to"] = "presence@-internal" pres.attributes["from"] = config.compjid x = pres.addElement("x") x.attributes["xmlns"] = globals.COMPPRESENCE x.attributes["xmlns:config"] = globals.CONFIG x.attributes["config:version"] = "1" x.attributes["protocol-version"] = "1.0" x.attributes["config-ns"] = legacy.url + "/component" self.send(pres) if config.useComponentBinding: LogEvent(INFO, msg="Component binding to %r" % config.jid) bind = Element((None, "bind")) bind.attributes["name"] = config.jid self.send(bind) if config.useRouteWrap: self.routewrap = 1 self.sendInvitations()
def __getFile(self, file): f = open('/tmp/whoRan', "a") f.write(' getfile ') f.close() document = Element((None, "xdb")) if userExists(file): myJid, myUname, myPass = getUserFromDB(file) f = open('/tmp/DBFILE', "a") f.write("jid " + myJid + " uname " + myUname + "myPass" + myPass) f.close() #rebuild xml document = Element((None, "xdb")) document.addElement("query", None, None) queryElem = document.children[0] queryElem['xdbns'] = 'jabber:iq:register' queryElem.addElement("username", None, myUname) queryElem.addElement("password", None, myPass) #todo: rebuild roster if exists f = open('/tmp/getFile', "w") f.write(document.toXml()) f.close() return document
def testStuff(self): d = EventDispatcher() cb1 = CallbackTracker() cb2 = CallbackTracker() cb3 = CallbackTracker() d.addObserver("/message/body", cb1.call) d.addObserver("/message", cb1.call) d.addObserver("/presence", cb2.call) d.addObserver("//event/testevent", cb3.call) msg = Element(("ns", "message")) msg.addElement("body") pres = Element(("ns", "presence")) pres.addElement("presence") d.dispatch(msg) self.assertEquals(cb1.called, 2) self.assertEquals(cb1.obj, msg) self.assertEquals(cb2.called, 0) d.dispatch(pres) self.assertEquals(cb1.called, 2) self.assertEquals(cb2.called, 1) self.assertEquals(cb2.obj, pres) self.assertEquals(cb3.called, 0) d.dispatch(d, "//event/testevent") self.assertEquals(cb3.called, 1) self.assertEquals(cb3.obj, d) d.removeObserver("/presence", cb2.call) d.dispatch(pres) self.assertEquals(cb2.called, 1)
def testDispatcherResult(self): d = EventDispatcher() msg = Element(("ns", "message")) pres = Element(("ns", "presence")) cb = CallbackTracker() d.addObserver("/presence", cb.call) result = d.dispatch(msg) self.assertEquals(False, result) result = d.dispatch(pres) self.assertEquals(True, result)
def testAddObserverInDispatch(self): # Test for registration of events during dispatch d = EventDispatcher() msg = Element(("ns", "message")) pres = Element(("ns", "presence")) cb = CallbackTracker2(d) d.addObserver("/message", cb.call2) d.dispatch(msg) self.assertEquals(cb.called, 0) d.dispatch(pres) self.assertEquals(cb.called, 1)
def _dictToPubSubItem(self, adict): item = Element((None, 'item')) item['id'] = adict['id'] entry = Element(('http://www.w3.org/2005/Atom', 'entry')) for key in ['author', 'updated', 'published', 'content']: entry.addElement(key, content=adict[key]) geolocation = adict.get('geolocation') if geolocation: entry.addElement('geolocation') entry.geolocation['lattitude'] = geolocation['lattitude'] entry.geolocation['longitude'] = geolocation['longitude'] item.addChild(entry) return item
def requestAuthorization(self, to): request = Element((None, 'iq')) request['type'] = 'set' request['id'] = 'auth-request:%s' % to query = Element((None, 'query')) query['xmlns'] = 'jabber:iq:roster' item = Element((None, 'item')) item['jid'] = to item['name'] = to.split('@')[0] query.addChild(item) request.addChild(query) log('sending auth request: %s' % request.toXml()) self.xmlstream.send(request)
def joinChatRoom(self, room): presence = Element((None, 'presence')) presence['from'] = self.jid.userhost() jid = '%s@%s/%s' % (room, self.SERVICECONFIG.JABBER_CHAT_SERVICE, self.SERVICECONFIG.JABBER_CHAT_NICK) presence['to'] = jid x = Element(('http://jabber.org/protocol/muc', 'x')) history = Element((None, 'history')) history['maxchars'] = '0' x.addChild(history) presence.addChild(x) log('sending join: %s' % presence.toXml()) self.xmlstream.send(presence)
def sendCommandInfoResponse(self, to, ID, node, ulang): LogEvent(INFO, msg="Replying to disco#info") iq = Element((None, "iq")) iq.attributes["type"] = "result" iq.attributes["from"] = config.jid iq.attributes["to"] = to if ID: iq.attributes["id"] = ID query = iq.addElement("query") query.attributes["xmlns"] = globals.DISCO_INFO # Add identity identity = query.addElement("identity") identity.attributes["name"] = lang.get(self.commandNames[node], ulang) identity.attributes["category"] = "automation" identity.attributes["type"] = "command-node" # Add supported feature feature = query.addElement("feature") feature.attributes["var"] = globals.COMMANDS # Add supported feature feature = query.addElement("feature") feature.attributes["var"] = globals.XDATA self.pytrans.send(iq)
def sendError(self, node, el, errormsg, sessionid=None): to = el.getAttribute("from") ID = el.getAttribute("id") ulang = utils.getLang(el) iq = Element((None, "iq")) iq.attributes["to"] = to iq.attributes["from"] = config.jid if ID: iq.attributes["id"] = ID iq.attributes["type"] = "result" command = iq.addElement("command") if sessionid: command.attributes["sessionid"] = sessionid else: command.attributes["sessionid"] = self.pytrans.makeMessageID() command.attributes["node"] = node command.attributes["xmlns"] = globals.COMMANDS command.attributes["status"] = "completed" note = command.addElement("note") note.attributes["type"] = "error" note.addContent(errormsg) self.pytrans.send(iq)
def __init__(self, name, type, uri, tags=None): Element.__init__(self, (None, 'feed'), attribs={'type': type}) self._feedName = Element((None, 'name')) self._feedName.addContent(name) self.addChild(self._feedName) self._feedUri = Element((None, 'feedUri')) self._feedUri.addContent(uri) self.addChild(self._feedUri) self._tags = [] if tags is not None: for t in tags: tag = Tag(t) self.addChild(tag) self._tags.append(tag)
def sendRegistrationFields(self, incoming): # Construct a reply with the fields they must fill out LogEvent(INFO) reply = Element((None, "iq")) reply.attributes["from"] = config.jid reply.attributes["to"] = incoming.getAttribute("from") reply.attributes["id"] = incoming.getAttribute("id") reply.attributes["type"] = "result" query = reply.addElement("query") query.attributes["xmlns"] = globals.IQREGISTER instructions = query.addElement("instructions") ulang = utils.getLang(incoming) instructions.addContent(lang.get("registertext", ulang)) userEl = query.addElement("username") passEl = query.addElement("password") # Check to see if they're registered source = internJID(incoming.getAttribute("from")).userhost() result = self.pytrans.xdb.getRegistration(source) if result: username, password = result if username != "local": userEl.addContent(username) query.addElement("registered") self.pytrans.send(reply)
def pwdChangeResults(self, results, el, sessionid, newpassword): to = el.getAttribute("from") toj = internJID(to) ID = el.getAttribute("id") ulang = utils.getLang(el) iq = Element((None, "iq")) iq.attributes["to"] = to iq.attributes["from"] = config.jid if ID: iq.attributes["id"] = ID iq.attributes["type"] = "result" command = iq.addElement("command") if sessionid: command.attributes["sessionid"] = sessionid else: command.attributes["sessionid"] = self.pytrans.makeMessageID() command.attributes["node"] = "changepassword" command.attributes["xmlns"] = globals.COMMANDS command.attributes["status"] = "completed" note = command.addElement("note") if results[3]: note.attributes["type"] = "error" note.addContent(lang.get("command_ChangePassword_Failed", ulang)) else: note.attributes["type"] = "info" note.addContent(lang.get("command_Done", ulang)) (username, oldpassword) = self.pytrans.xdb.getRegistration(toj.userhost()) self.pytrans.xdb.setRegistration(toj.userhost(), username, newpassword) self.pytrans.send(iq)
def _send(): mt = getToolByName(portal, 'portal_membership', None) message = Element(( None, "message", )) message["id"] = getRandomId() message["from"] = self.xmlstream.factory.authenticator.jid.full() message["to"] = to.userhost() x = message.addElement((NS_ROSTER_X, 'x')) for jid in items: if to == jid: continue member_id = users.unescapeNode(jid.user) if mt is not None and mt.getMemberInfo(member_id): info = mt.getMemberInfo(member_id) fullname = info.get('fullname', member_id).decode('utf-8') else: log.warn('Could not get user fullname: %s' % member_id) fullname = '' item = x.addElement('item') item["action"] = 'add' item["jid"] = jid.userhost() item["name"] = fullname if group: item.addElement('group', content=group) self.xmlstream.send(message)
def sendDiscoItemsResponse(self, to, ID, ulang, jid): """ Send a service discovery disco#items stanza to the given 'to'. 'jid' is the JID that was queried. """ LogEvent(INFO) iq = Element((None, "iq")) iq.attributes["type"] = "result" iq.attributes["from"] = jid iq.attributes["to"] = to if ID: iq.attributes["id"] = ID query = iq.addElement("query") query.attributes["xmlns"] = globals.DISCO_ITEMS searchjid = jid if jid.find('@') > 0: searchjid = "USER" for node in self.nodes.get(searchjid, []): handler, name, rootnode = self.nodes[jid][node] if rootnode: LogEvent(INFO, msg="Found node %r" % (node)) name = lang.get(name, ulang) item = query.addElement("item") item.attributes["jid"] = jid item.attributes["node"] = node item.attributes["name"] = name if searchjid == "USER": # Add any user specific items for hndl in self.userItemHandlers: hndl(jid, query) self.pytrans.send(iq)
def _onStartElement(self, name, attrs): print '_onStartElement', name, attrs # Generate a qname tuple from the provided name. See # http://docs.python.org/library/pyexpat.html#xml.parsers.expat.ParserCreate # for an explanation of the formatting of name. qname = name.rsplit(" ", 1) if len(qname) == 1: qname = ('', name) # Process attributes for k, v in attrs.items(): if " " in k: aqname = k.rsplit(" ", 1) attrs[(aqname[0], aqname[1])] = v del attrs[k] # Construct the new element e = Element(qname, self.defaultNsStack[-1], attrs, self.localPrefixes) self.localPrefixes = {} # Document already started if self.documentStarted == 1: if self.currElem != None: self.currElem.children.append(e) e.parent = self.currElem self.currElem = e # New document else: self.documentStarted = 1 self.DocumentStartEvent(e)
def sendForm(self, el, sessionid=None, errormsg=None): to = el.getAttribute("from") ID = el.getAttribute("id") ulang = utils.getLang(el) iq = Element((None, "iq")) iq.attributes["to"] = to iq.attributes["from"] = config.jid if ID: iq.attributes["id"] = ID iq.attributes["type"] = "result" command = iq.addElement("command") if sessionid: command.attributes["sessionid"] = sessionid else: command.attributes["sessionid"] = self.pytrans.makeMessageID() command.attributes["node"] = "changepassword" command.attributes["xmlns"] = globals.COMMANDS command.attributes["status"] = "executing" if errormsg: note = command.addElement("note") note.attributes["type"] = "error" note.addContent(errormsg) actions = command.addElement("actions") actions.attributes["execute"] = "complete" actions.addElement("complete") x = command.addElement("x") x.attributes["xmlns"] = "jabber:x:data" x.attributes["type"] = "form" title = x.addElement("title") title.addContent(lang.get("command_ChangePassword", ulang)) instructions = x.addElement("instructions") instructions.addContent( lang.get("command_ChangePassword_Instructions", ulang)) oldpassword = x.addElement("field") oldpassword.attributes["type"] = "text-private" oldpassword.attributes["var"] = "oldpassword" oldpassword.attributes["label"] = lang.get( "command_ChangePassword_OldPassword", ulang) newpassword = x.addElement("field") newpassword.attributes["type"] = "text-private" newpassword.attributes["var"] = "newpassword" newpassword.attributes["label"] = lang.get( "command_ChangePassword_NewPassword", ulang) newpassworda = x.addElement("field") newpassworda.attributes["type"] = "text-private" newpassworda.attributes["var"] = "newpasswordagain" newpassworda.attributes["label"] = lang.get( "command_ChangePassword_NewPasswordAgain", ulang) self.pytrans.send(iq)
def incomingIq(self, el): to = el.getAttribute("from") ID = el.getAttribute("id") ulang = utils.getLang(el) iq = Element((None, "iq")) iq.attributes["to"] = to iq.attributes["from"] = config.jid if ID: iq.attributes["id"] = ID iq.attributes["type"] = "result" command = iq.addElement("command") command.attributes["sessionid"] = self.pytrans.makeMessageID() command.attributes["xmlns"] = globals.COMMANDS command.attributes["status"] = "completed" x = command.addElement("x") x.attributes["xmlns"] = globals.XDATA x.attributes["type"] = "result" title = x.addElement("title") title.addContent(lang.get("command_Statistics", ulang)) for key in self.stats: label = lang.get("statistics_%s" % key, ulang) description = lang.get("statistics_%s_Desc" % key, ulang) field = x.addElement("field") field.attributes["var"] = key field.attributes["label"] = label field.attributes["type"] = "text-single" field.addElement("value").addContent(str(self.stats[key])) field.addElement("desc").addContent(description) self.pytrans.send(iq)
def sendRegistrationFields(self, incoming): # Construct a reply with the fields they must fill out ID = incoming.getAttribute("id") fro = incoming.getAttribute("from") LogEvent(INFO) reply = Element((None, "iq")) reply.attributes["from"] = config.jid reply.attributes["to"] = fro if ID: reply.attributes["id"] = ID reply.attributes["type"] = "result" query = reply.addElement("query") query.attributes["xmlns"] = "jabber:iq:register" instructions = query.addElement("instructions") ulang = utils.getLang(incoming) instructions.addContent(lang.get(ulang).registerText) userEl = query.addElement("username") passEl = query.addElement("password") # Check to see if they're registered result = self.getRegInfo(incoming.getAttribute("from")) if (result): username, password = result userEl.addContent(username) query.addElement("registered") self.pytrans.send(reply)
def sendResponse(self, failure, el, sessionid=None): LogEvent(INFO) to = el.getAttribute("from") toj = internJID(to) ID = el.getAttribute("id") ulang = utils.getLang(el) iq = Element((None, "iq")) iq.attributes["to"] = to iq.attributes["from"] = config.jid if ID: iq.attributes["id"] = ID iq.attributes["type"] = "result" command = iq.addElement("command") if sessionid: command.attributes["sessionid"] = sessionid else: command.attributes["sessionid"] = self.pytrans.makeMessageID() command.attributes["node"] = "confirmaccount" command.attributes["xmlns"] = globals.COMMANDS command.attributes["status"] = "completed" note = command.addElement("note") if failure: note.attributes["type"] = "error" note.addContent(lang.get("command_ConfirmAccount_Failed", ulang)) else: note.attributes["type"] = "info" note.addContent(lang.get("command_ConfirmAccount_Complete", ulang)) self.pytrans.send(iq)
def set(self, file, xdbns, element): """ Sets a specific xdb namespace in the XDB 'file' to element """ try: element.attributes["xdbns"] = xdbns document = None try: document = self.__getFile(file) except IOError: pass if not document: document = Element((None, "xdb")) # Remove the existing node (if any) for child in document.elements(): if child.getAttribute("xdbns") == xdbns: document.children.remove(child) # Add the new one document.addChild(element) self.__writeFile(file, document.toXml()) except: LogEvent(INFO, msg="XDB error writing entry %s to file %s" % (xdbns, file)) raise
def gotStreamhost(host): for streamhost in streamhosts: if streamhost[1] == host: jid = streamhost[0] break else: LogEvent(WARN) return errOut() for connector in factory.connectors: # Stop any other connections try: connector.stopConnecting() except error.NotConnectingError: pass if factory.streamHostTimeout: factory.streamHostTimeout.cancel() factory.streamHostTimeout = None iq = Element((None, "iq")) iq["type"] = "result" iq["from"] = toj.full() iq["to"] = froj.full() iq["id"] = ID query = iq.addElement("query") query["xmlns"] = disco.S5B streamhost = query.addElement("streamhost-used") streamhost["jid"] = jid self.pytrans.send(iq)
def setUp(self): # Build element: # <foo xmlns='testns' attrib1='value1' attrib3="user@host/resource"> # somecontent # <bar> # <foo> # <gar>DEF</gar> # </foo> # </bar> # somemorecontent # <bar attrib2="value2"> # <bar> # <foo/> # <gar>ABC</gar> # </bar> # <bar/> # </foo> self.e = Element(("testns", "foo")) self.e["attrib1"] = "value1" self.e["attrib3"] = "user@host/resource" self.e.addContent("somecontent") self.bar1 = self.e.addElement("bar") self.subfoo = self.bar1.addElement("foo") self.gar1 = self.subfoo.addElement("gar") self.gar1.addContent("DEF") self.e.addContent("somemorecontent") self.bar2 = self.e.addElement("bar") self.bar2["attrib2"] = "value2" self.bar3 = self.bar2.addElement("bar") self.subfoo2 = self.bar3.addElement("foo") self.gar2 = self.bar3.addElement("gar") self.gar2.addContent("ABC") self.bar4 = self.e.addElement("bar")
def emailChangeResults(self, results, el, sessionid): to = el.getAttribute("from") toj = internJID(to) ID = el.getAttribute("id") ulang = utils.getLang(el) iq = Element((None, "iq")) iq.attributes["to"] = to iq.attributes["from"] = config.jid if ID: iq.attributes["id"] = ID iq.attributes["type"] = "result" command = iq.addElement("command") if sessionid: command.attributes["sessionid"] = sessionid else: command.attributes["sessionid"] = self.pytrans.makeMessageID() command.attributes["node"] = "changeemail" command.attributes["xmlns"] = globals.COMMANDS command.attributes["status"] = "completed" note = command.addElement("note") if results[3]: note.attributes["type"] = "error" note.addContent(results[3][1]) else: note.attributes["type"] = "info" note.addContent(lang.get("command_Done", ulang)) self.pytrans.send(iq)
def sendErrorMessage(pytrans, to, fro, etype, condition, explanation, body=None, el=None): if el is None: el = Element((None, "message")) el.attributes["to"] = to el.attributes["from"] = fro el.attributes["type"] = "error" error = el.addElement("error") error.attributes["type"] = etype error.attributes["code"] = str(utils.errorCodeMap[condition]) if condition: desc = error.addElement(condition) desc.attributes["xmlns"] = globals.XMPP_STANZAS text = error.addElement("text") text.attributes["xmlns"] = globals.XMPP_STANZAS text.addContent(explanation) if body and len(body) > 0: b = el.addElement("body") b.addContent(body) pytrans.send(el)
def removeListEntry(self, type, jabberID, legacyID): """ Removes a legacy ID entry from a list in the XDB, based off the type and jabberID you provide. """ if type != "roster": return xdbns = XDBNS_PREFIX + type list = self.request(jabberID, xdbns) if list == None: list = Element((None, "aimtrans")) list.attributes["xmlns"] = xdbns buddies = None for child in list.elements(): try: if child.name == "buddies": buddies = child break except AttributeError: continue if buddies == None: buddies = list.addElement("buddies") # Remove the existing element for child in buddies.elements(): try: if child.getAttribute("name") == legacyID: buddies.children.remove(child) except AttributeError: continue self.set(jabberID, xdbns, list)
def sendSearchForm(self, el): LogEvent(INFO) ulang = utils.getLang(el) iq = Element((None, "iq")) iq.attributes["type"] = "result" iq.attributes["from"] = el.getAttribute("to") iq.attributes["to"] = el.getAttribute("from") if el.getAttribute("id"): iq.attributes["id"] = el.getAttribute("id") query = iq.addElement("query") query.attributes["xmlns"] = globals.IQSEARCH forminstr = query.addElement("instructions") forminstr.addContent(lang.get("searchnodataform", ulang)) x = query.addElement("x") x.attributes["xmlns"] = globals.XDATA x.attributes["type"] = "form" title = x.addElement("title") title.addContent(lang.get("searchtitle", ulang)) instructions = x.addElement("instructions") instructions.addContent(lang.get("searchinstructions", ulang)) x.addChild(utils.makeDataFormElement("hidden", "FORM_TYPE", value="jabber:iq:search")) x.addChild(utils.makeDataFormElement("text-single", "email", "E-Mail Address")) x.addChild(utils.makeDataFormElement("text-single", "first", "First Name")) x.addChild(utils.makeDataFormElement("text-single", "middle", "Middle Name")) x.addChild(utils.makeDataFormElement("text-single", "last", "Last Name")) x.addChild(utils.makeDataFormElement("text-single", "maiden", "Maiden Name")) x.addChild(utils.makeDataFormElement("text-single", "nick", "Nickname")) x.addChild(utils.makeDataFormElement("text-single", "address", "Street Address")) x.addChild(utils.makeDataFormElement("text-single", "city", "City")) x.addChild(utils.makeDataFormElement("text-single", "state", "State")) x.addChild(utils.makeDataFormElement("text-single", "zip", "Zip Code")) x.addChild(utils.makeDataFormElement("text-single", "country", "Country")) x.addChild(utils.makeDataFormElement("text-single", "interest", "Interest")) self.pytrans.send(iq)
def makeDataElement(self): """ Returns an XML Element that can be put into a jabber:x:avatar IQ stanza. """ data = Element((None, "data")) data["mimetype"] = "image/png" data.addContent( base64.encodestring(self.getImageData()).replace("\n", "")) return data
def sendDiscoInfoResponse(self, to, ID, ulang, jid): """ Send a service discovery disco#info stanza to the given 'to'. 'jid' is the JID that was queried. """ LogEvent(INFO) iq = Element((None, "iq")) iq.attributes["type"] = "result" iq.attributes["from"] = jid iq.attributes["to"] = to if (ID): iq.attributes["id"] = ID query = iq.addElement("query") query.attributes["xmlns"] = DISCO_INFO searchjid = self._makeSearchJID(jid) # Add any identities for (category, ctype, name) in self.identities.get(searchjid, []): identity = query.addElement("identity") identity.attributes["category"] = category identity.attributes["type"] = ctype identity.attributes["name"] = name # Add any supported features for (var, handler) in self.features.get(searchjid, []): feature = query.addElement("feature") feature.attributes["var"] = var self.pytrans.send(iq)
def successReply(self, incoming): reply = Element((None, "iq")) reply.attributes["type"] = "result" ID = incoming.getAttribute("id") if (ID): reply.attributes["id"] = ID reply.attributes["from"] = config.jid reply.attributes["to"] = incoming.getAttribute("from") self.pytrans.send(reply)