def toElement(self): el = Element((collab.COLLAB_NS, 'issuer')) el.addElement('name', content=self.name) factors = el.addElement('factors') for f in self.factors: factors.addChild(f.toElement()) return el
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 getRandomPortfolio(min_size=10): portfolio = Element((collab.COLLAB_NS, 'portfolio')) #assets assets = portfolio.addElement('assets') no_assets = random.randrange(min_size,20) no_issuers = int(no_assets/ratio) for i in xrange(no_assets): a = assets.addElement('asset') a.addElement('id').addContent(str(i)) a.addElement('name').addContent('asset%i' % i) a.addElement('default_probability').addContent(str(float(i)/div)) #issuers issuers = portfolio.addElement('issuers') for i in xrange(no_issuers): iss = issuers.addElement('issuer') iss.addElement('id').addContent(str(i)) iss.addElement('name').addContent('issuer%i' % i) fs = iss.addElement('factors') for j in xrange(random.randrange(1, 5)): f = fs.addElement('factor') f.addElement('name').addContent('factor%i' % j) f.addElement('weight').addContent(str(float(j)/div)) #asset issuer map aimap = portfolio.addElement('asset_issuer_map') for i in xrange(no_assets): a = aimap.addElement('asset') a.addElement('id').addContent(str(i)) a.addElement('issuer').addElement('id').addContent(str(i%no_issuers)) return portfolio
def test_fromElement_bad(self): el = Element((collab.COLLAB_NS, 'wrong')) el.addElement('runs', content='100') def doIt(): p = simulation.Progress.fromElement(el) self.assertRaises(simulation.InvalidProgressError, doIt)
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 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 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) bodywritten = False # no <body/> in message for child in el.elements(): # try find in el if child.name == 'body': # <body/> already in el if body and len(body) > 0: # necessary add other info to it body_txt = child.__str__() child.addContent(body_txt + '\n' + body) bodywritten = True if not bodywritten and body and len(body) > 0: # <body/> in el don't found b = el.addElement('body') b.addContent(body) pytrans.send(el)
def send(self, to, body, subject=None, mtype=None, delay=None): print 'start sending' el = Element((None, "message")) el.attributes["to"] = to el.attributes["from"] = self.juser el.attributes["id"] = '111111' if(subject): subj = el.addElement("subject") subj.addContent(subject) if(mtype): el.attributes["type"] = mtype if(delay): x = el.addElement("x") x.attributes["xmlns"] = "jabber:x:delay" x.attributes["from"] = fro x.attributes["stamp"] = delay b = el.addElement("body") b.addContent(body) self.theXmlstream.send(el) print 'done sending'
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 getPortfolio(): portfolio = Element((collab.COLLAB_NS, 'portfolio')) #assets assets = portfolio.addElement('assets') for i in xrange(num_assets): a = assets.addElement('asset') a.addElement('id').addContent(str(i)) a.addElement('name').addContent('asset%i' % i) a.addElement('default_probability').addContent(str(float(i)/div)) #issuers issuers = portfolio.addElement('issuers') for i in xrange(num_issuers): iss = issuers.addElement('issuer') iss.addElement('id').addContent(str(i)) iss.addElement('name').addContent('issuer%i' % i) fs = iss.addElement('factors') for j in xrange(num_factors): f = fs.addElement('factor') f.addElement('name').addContent('factor%i' % j) f.addElement('weight').addContent(str(float(j)/div)) #asset issuer map aimap = portfolio.addElement('asset_issuer_map') for i in xrange(num_assets): a = aimap.addElement('asset') a.addElement('id').addContent(str(i)) a.addElement('issuer').addElement('id').addContent(str(i%num_issuers)) return portfolio
def toElement(self): el = Element((collab.COLLAB_NS, 'portfolio')) el.addElement('name', content=self.name) ass_el = el.addElement('assets') for a in self.assets: ass_el.addChild(a.toElement()) return el
def makePhotoElement(self): """ Returns an XML Element that can be put into the vCard. """ photo = Element((None, "PHOTO")) type = photo.addElement("TYPE") type.addContent("image/png") binval = photo.addElement("BINVAL") binval.addContent(base64.encodestring(self.getImageData()).replace("\n", "")) return photo
def test_fromElement_noAssets(self): el = Element((collabNs, 'portfolio')) el.addElement('name', content='port') def doIt(): p = portfolio.Portfolio.fromElement(el) self.assertRaises(portfolio.InvalidPortfolioError, doIt)
def test_fromElement(self): el = Element((collabNs, 'factor')) el.addElement('name', content='fac') el.addElement('weight', content='0.5') f = portfolio.Factor.fromElement(el) self.assertEquals(f.name, 'fac') self.assertEquals(f.weight, 0.5)
def test_fromElement_noWeight(self): el = Element((collabNs, 'factor')) el.addElement('name', content='fac') def doIt(): f = portfolio.Factor.fromElement(el) self.assertRaises(portfolio.InvalidFactorError, doIt)
def test_Issuer_fromElement_factorsButNoneInThere(self): expected = Element((collabNs, 'issuer')) expected.addElement('name', content='iss') fs_el = expected.addElement('factors') i = portfolio.Issuer.fromElement(expected) self.assertEquals(i.name, 'iss') self.assertEquals(i.factors, set())
def test_toElement(self): p = simulation.Progress(100) el = p.toElement() expected = Element((collab.COLLAB_NS, 'progress')) expected.addElement('runs', content='100') self.assertEquals(el.toXml(), expected.toXml())
def test_Issuer_fromElement_noFactors(self): expected = Element((collabNs, 'issuer')) expected.addElement('name', content='iss') def doIt(): i = portfolio.Issuer.fromElement(expected) self.assertRaises(portfolio.InvalidIssuerError, doIt)
def test_fromElement_noAssetsInAssetsElement(self): el = Element((collabNs, 'portfolio')) el.addElement('name', content='port') assets_el = el.addElement('assets') p = portfolio.Portfolio.fromElement(el) self.assertEquals(p.name, 'port') self.assertEquals(p.assets, set())
def makePhotoElement(self): """ Returns an XML Element that can be put into the vCard. """ photo = Element((None, "PHOTO")) type = photo.addElement("TYPE") type.addContent("image/png") binval = photo.addElement("BINVAL") binval.addContent( base64.encodestring(self.getImageData()).replace("\n", "")) return photo
def test_toElement(self): f = portfolio.Factor('fac', 0.5) el = f.toElement() expected = Element((collabNs, 'factor')) expected.addElement('name', content='fac') expected.addElement('weight', content='0.5') self.assertEquals(el.toXml(), expected.toXml()) self.assertEquals(el.uri, collabNs)
def test_fromElement_defaults(self): el = Element((collabNs, 'asset')) el.addElement('name', content='ass') ass = portfolio.Asset.fromElement(el) self.assertEquals(ass.name, 'ass') self.assertEquals(ass.dp, 1.0) self.assertEquals(ass.recovery, 1.0) self.assertEquals(ass.notional, 100.0) self.assertTrue(ass.issuer is None)
def test_fromElement_bad(self): el = Element((None, 'actions')) el['execute'] = 'next' el.addElement('next') el.addElement('wrong') a = Actions.fromElement(el) self.assertEquals(len(a.actions), 1) self.assertTrue('next' in a.actions) self.assertEquals(a.default, 'next')
def test_fromElement(self): el = Element((collabNs, 'asset')) el.addElement('name', content='ass') el.addElement('dp', content='0.1') el.addElement('recovery', content='0.1') el.addElement('notional', content='200.0') i_el = el.addElement('issuer') i_el.addElement('name', content='iss') fs_el = i_el.addElement('factors') f1_el = fs_el.addElement('factor') f1_el.addElement('name', content='f1') f1_el.addElement('weight', content='0.1') f2_el = fs_el.addElement('factor') f2_el.addElement('name', content='f2') f2_el.addElement('weight', content='0.2') ass = portfolio.Asset.fromElement(el) self.assertEquals(ass.name, 'ass') self.assertEquals(ass.dp, 0.1) self.assertEquals(ass.recovery, 0.1) self.assertEquals(ass.notional, 200.0) i = ass.issuer self.assertEquals(i.name, 'iss') fs = i.factors self.assertEquals(len(fs), 2) self.assertTrue(checkFactor('f1', 0.1, fs)) self.assertTrue(checkFactor('f2', 0.2, fs))
def sendMessage(self, to, body): """ Send a text message """ message = Element((None, "message")) message["id"] = getRandomId() message["from"] = self.xmlstream.factory.authenticator.jid.full() message["to"] = to.full() message["type"] = "chat" message.addElement("body", content=body) self.xmlstream.send(message) return True
def test_toElement(self): a = Actions() a.setDefault('next') a.add('prev') el = Element((None, 'actions')) el['execute'] = 'next' el.addElement('prev') el.addElement('next') self.assertEquals(a.toElement().toXml(), el.toXml())
def messageOobMode(self): LogEvent(INFO, self.ident) filename = self.session.pytrans.ftOOBReceive.putFile( self, self.legacyftp.filename) m = Element((None, "message")) m.attributes["to"] = self.session.jabberID m.attributes["from"] = self.senderJID m.addElement("body").addContent(config.ftOOBRoot + "/" + filename) x = m.addElement("x") x.attributes["xmlns"] = disco.XOOB x.addElement("url").addContent(config.ftOOBRoot + "/" + filename) self.session.pytrans.send(m)
def formRegEntry(username, password): """ Returns a domish.Element representation of the data passed. This element will be written to the XDB spool file """ reginfo = Element((None, "query")) reginfo.attributes["xmlns"] = "jabber:iq:register" userEl = reginfo.addElement("username") userEl.addContent(username) passEl = reginfo.addElement("password") passEl.addContent(password) return reginfo
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 sendUserInvite(self, fro): """ Sends the invitation out to the Jabber user to join this room """ el = Element((None, "message")) el.attributes["from"] = fro el.attributes["to"] = self.user() body = el.addElement("body") text = lang.get("groupchatinvite", self.session.lang) % (self.roomJID()) body.addContent(text) x = el.addElement("x") x.attributes["jid"] = self.roomJID() x.attributes["xmlns"] = globals.XCONFERENCE LogEvent(INFO,self.session.jabberID) self.session.pytrans.send(el)
def testOrderedXPathDispatch(self): d = EventDispatcher() cb = OrderedCallbackTracker() d.addObserver("/message/body", cb.call2) d.addObserver("/message", cb.call3, -1) d.addObserver("/message/body", cb.call1, 1) msg = Element(("ns", "message")) msg.addElement("body") d.dispatch(msg) self.assertEquals(cb.callList, [cb.call1, cb.call2, cb.call3], "Calls out of order: %s" % repr([c.__name__ for c in cb.callList]))
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['latitude'] = geolocation['latitude'] entry.geolocation['longitude'] = geolocation['longitude'] item.addChild(entry) return item
def sendUserInvite(self, fro): """ Sends the invitation out to the Jabber user to join this room """ LogEvent(INFO, self.roomJID(), "Sending invitation to user") el = Element((None, "message")) el.attributes["from"] = fro el.attributes["to"] = self.user() body = el.addElement("body") text = lang.get(self.session.lang).groupchatInvite % (self.roomJID()) body.addContent(text) x = el.addElement("x") x.attributes["jid"] = self.roomJID() x.attributes["xmlns"] = disco.XCONFERENCE self.session.pytrans.send(el)
def testOrderedXPathDispatch(self): d = EventDispatcher() cb = OrderedCallbackTracker() d.addObserver("/message/body", cb.call2) d.addObserver("/message", cb.call3, -1) d.addObserver("/message/body", cb.call1, 1) msg = Element(("ns", "message")) msg.addElement("body") d.dispatch(msg) self.assertEquals( cb.callList, [cb.call1, cb.call2, cb.call3], "Calls out of order: %s" % repr([c.__name__ for c in cb.callList]))
def sendMessage(self, to, body): """ Send a text message """ message = Element(( None, "message", )) message["id"] = getRandomId() message["from"] = self.xmlstream.factory.authenticator.jid.full() message["to"] = to.full() message["type"] = 'chat' message.addElement('body', content=body) self.xmlstream.send(message) return True
def test_Issuer_toElement(self): fs = set([portfolio.Factor('f1', 0.1)]) i = portfolio.Issuer('iss', fs) el = i.toElement() expected = Element((collabNs, 'issuer')) expected.addElement('name', content='iss') fs_el = expected.addElement('factors') f1_el = fs_el.addElement('factor') f1_el.addElement('name', content='f1') f1_el.addElement('weight', content='0.1') self.assertEquals(el.toXml(), expected.toXml()) self.assertEquals(el.uri, collabNs)
def sendXHTMLMessage(self, to, body, xhtml_body): """ Send an HTML message. """ message = Element((NS_CLIENT, "message")) message["id"] = getRandomId() message["from"] = self.xmlstream.factory.authenticator.jid.full() message["to"] = to.full() message["type"] = "chat" message.addElement("body", content=body) html = message.addElement((XHTML_IM, "html")) html_body = html.addElement((XHTML, "body")) html_body.addRawXml(xhtml_body) self.xmlstream.send(message) return True
def sendPresence(pytrans, to, fro, show=None, status=None, priority=None, ptype=None, avatarHash=None, nickname=None, payload=[], url=None): if ptype in ["subscribe", "subscribed", "unsubscribe", "unsubscribed"]: to = internJID(to).userhost() fro = internJID(fro).userhost() el = Element((None, "presence")) el.attributes["to"] = to el.attributes["from"] = fro if ptype: el.attributes["type"] = ptype if show: s = el.addElement("show") s.addContent(utils.xmlify(show)) if status: s = el.addElement("status") s.addContent(utils.xmlify(status)) if priority: s = el.addElement("priority") s.addContent(priority) if url: s = el.addElement("x") s.attributes["xmlns"] = globals.XOOB s = el.addElement("url") s.addContent(url) if not ptype: if avatarHash and not config.disableAvatars and not config.disableVCardAvatars: x = el.addElement("x") x.attributes["xmlns"] = globals.VCARDUPDATE p = x.addElement("photo") p.addContent(avatarHash) if nickname: x = el.addElement("x") x.attributes["xmlns"] = globals.VCARDUPDATE n = x.addElement("nickname") n.addContent(nickname) if avatarHash and not config.disableAvatars and not config.disableIQAvatars: x = el.addElement("x") x.attributes["xmlns"] = globals.XAVATAR h = x.addElement("hash") h.addContent(avatarHash) if nickname and ptype == "subscribe": n = el.addElement("nick") n.attributes["xmlns"] = globals.NICK n.addContent(nickname) if payload: for p in payload: el.addChild(p) pytrans.send(el)
def sendPresence(pytrans, to, fro, show=None, status=None, priority=None, ptype=None, avatarHash=None, nickname=None, payload=[], url=None): if ptype in ["subscribe", "subscribed", "unsubscribe", "unsubscribed"]: to = internJID(to).userhost() fro = internJID(fro).userhost() el = Element((None, "presence")) el.attributes["to"] = to el.attributes["from"] = fro if ptype: el.attributes["type"] = ptype if show: s = el.addElement("show") s.addContent(utils.xmlify(show)) if status: s = el.addElement("status") s.addContent(utils.xmlify(status)) if priority: s = el.addElement("priority") s.addContent(priority) if url: s = el.addElement("x") s.attributes["xmlns"] = globals.XOOB s = el.addElement("url") s.addContent(url) if not ptype: if avatarHash and not config.disableAvatars and not config.disableVCardAvatars: x = el.addElement("x") x.attributes["xmlns"] = globals.VCARDUPDATE p = x.addElement("photo") p.addContent(avatarHash) if nickname: x = el.addElement("x") x.attributes["xmlns"] = globals.VCARDUPDATE n = x.addElement("nickname") n.addContent(nickname) if avatarHash and not config.disableAvatars and not config.disableIQAvatars: x = el.addElement("x") x.attributes["xmlns"] = globals.XAVATAR h = x.addElement("hash") h.addContent(avatarHash) if nickname and ptype == "subscribe": n = el.addElement("nick") n.attributes["xmlns"] = globals.NICK n.addContent(nickname) if payload: for p in payload: el.addChild(p) pytrans.send(el)
def test_onGotItem_noParams(self): cdm = CorrelatedDefaultsManager(testjid) cdm.broadcastStart = Mock() cdm.broadcastStop = Mock() cdm.broadcastLogs = Mock() item = Element((pubsub.NS_PUBSUB_EVENT, 'item')) item['id'] = str(1) item.addElement('stuff', content='stuff that isnt parameters') out = yield cdm.onGotItem(item) self.assertFalse(cdm.broadcastStart.called) self.assertFalse(cdm.broadcastStop.called) self.assertFalse(cdm.broadcastLogs.called)
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 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 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 request(self, file, xdbns): #rebuild xml #todo: build roster if exists f = open('/tmp/whoRan', "a") f.write(' request ') f.close() document = Element((None, "xdb")) if userExists(file): if xdbns == 'jabber:iq:register': jid, myUname, myPass = getUserFromDB(file) document.addElement("query", None, None) queryElem = document.children[0] queryElem['xdbns'] = 'jabber:iq:register' queryElem.addElement("username", None, myUname) queryElem.addElement("password", None, myPass) return document
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 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 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 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 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 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 sendCompletedForm(self, el, sessionid=None): to = el.getAttribute('from') ID = el.getAttribute('id') ulang = utils.getLang(el) iq = Element((None, 'iq')) iq.attributes = {'to': to, 'from': config.jid, 'type': 'result'} if ID: iq.attributes['id'] = ID command = iq.addElement('command') command.attributes = { 'node': 'settings', 'xmlns': globals.COMMANDS, 'status': 'completed' } if sessionid: command.attributes['sessionid'] = sessionid else: command.attributes['sessionid'] = self.pytrans.makeMessageID() note = command.addElement('note', None, lang.get('settings_changed')) note.attributes['type'] = 'info' x = command.addElement('x') x.attributes = {'xmlns': 'jabber:x:data', 'type': 'form'} x.addElement('title', None, lang.get('command_Settings')) x.addElement('instructions', None, lang.get('settings_changed')) self.pytrans.send(iq)
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 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 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 formRegEntry(self, username, password): """ Returns a domish.Element representation of the data passed. This element will be written to the XDB spool file """ reginfo = Element((None, "query")) reginfo.attributes["xmlns"] = XDBNS_REGISTER userEl = reginfo.addElement("username") userEl.addContent(username) if config.xdbDriver_xmlfiles.get("format", "") == "encrypted": passEl = reginfo.addElement("encpassword") passEl.addContent(utils.encryptPassword(password)) else: passEl = reginfo.addElement("password") passEl.addContent(password) return reginfo
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 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 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 sendXHTMLMessage(self, to, body, xhtml_body): """ Send an HTML message. """ message = Element(( NS_CLIENT, "message", )) message["id"] = getRandomId() message["from"] = self.xmlstream.factory.authenticator.jid.full() message["to"] = to.full() message["type"] = 'chat' message.addElement('body', content=body) html = message.addElement((XHTML_IM, 'html')) html_body = html.addElement((XHTML, 'body')) html_body.addRawXml(xhtml_body) self.xmlstream.send(message) return True