def user_sms_form(numbers): xform = xmpp.protocol.DataForm(typ='form', title=i18n.GATE_SMS_COMMAND) instr = i18n.GATE_SMS_COMMAND_INSTRUCTION xform.setInstructions(instr) phone = xform.setField('number') phone.setAttr('type', 'list-single') phone.setAttr('label', i18n.NUMBER) phs = [(x,x) for x in numbers] default = xmpp.Node('value') default.setData(numbers[0]) phone_pool = [default] for k,v in phs: phone_option = xmpp.Node('option', attrs={'label':k}) phone_option.setTagData('value', v) phone_pool.append(phone_option) phone.setPayload(phone_pool, add=1) text = xform.setField('text') text.setAttr('type', 'text-multi') text.setAttr('label', i18n.TEXT) translit = xform.setField('translit') translit.setAttr('type', 'boolean') translit.setAttr('label', i18n.TRANSLIT) translit.setTagData('value', '0') return xform
def getFeatures(destination, source, ns, disco=False): if destination == TransportID: features = TransportFeatures else: features = UserFeatures payload = [xmpp.Node("identity", IDENTIFIER)] if source in ADMIN_JIDS and disco: payload.append( xmpp.Node( "item", { "node": Node.USERS_ONLINE, "name": Node.USERS_ONLINE, "jid": TransportID })) payload.append( xmpp.Node( "item", { "node": Node.USERS_TOTAL, "name": Node.USERS_TOTAL, "jid": TransportID })) if ns == xmpp.NS_DISCO_INFO: for key in features: node = xmpp.Node("feature", {"var": key}) payload.append(node) return payload
def iq_display(self, iq): """ Get the VNC display used in the virtual machine. @type iq: xmpp.Protocol.Iq @param iq: the received IQ @rtype: xmpp.Protocol.Iq @return: a ready to send IQ containing the result of the action """ reply = iq.buildReply("result") try: if not self.entity.domain: return iq.buildReply('ignore') ports = self.display() if not ports: payload = xmpp.Node("display", attrs={}) else: payload = xmpp.Node("display", attrs={ "port": str(ports["direct"]), "proxy": str(ports["proxy"]), "host": self.entity.ipaddr, "onlyssl": str(ports["onlyssl"]), "supportssl": str(ports["supportssl"]) }) reply.setQueryPayload([payload]) except libvirt.libvirtError as ex: reply = build_error_iq(self, ex, iq, ex.get_error_code(), ns=archipel.archipelLibvirtEntity. ARCHIPEL_NS_LIBVIRT_GENERIC_ERROR) except Exception as ex: reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_VM_VNC) return reply
def iq_getiso(self, iq): """ Get the virtual cdrom ISO of the virtual machine. @type iq: xmpp.Protocol.Iq @param iq: the received IQ @rtype: xmpp.Protocol.Iq @return: a ready to send IQ containing the result of the action """ try: nodes = [] isos = os.listdir(self.entity.folder) for iso in isos: if self._is_file_an_iso(os.path.join(self.entity.folder, iso)): node = xmpp.Node(tag="iso", attrs={"name": iso, "path": os.path.join(self.entity.folder, iso)}) nodes.append(node) sharedisos = os.listdir(self.shared_isos_folder) for iso in sharedisos: if self._is_file_an_iso(os.path.join(self.shared_isos_folder, iso)): node = xmpp.Node(tag="iso", attrs={"name": iso, "path": os.path.join(self.shared_isos_folder, iso)}) nodes.append(node) reply = iq.buildReply("result") reply.setQueryPayload(nodes) self.entity.log.info("Info about iso sent.") except Exception as ex: reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_DRIVES_GETISO) return reply
def parseRSS(self): """ Parse the content of the database, update the feed, create the answer node. """ sources = self.cursor.execute("SELECT * FROM vmcastsources") nodes = [] tmp_cursor = self.database_connection.cursor() content = [] ## this will avoid to parse two times the content of the cursor if we udpate for values in sources: content.append(values) for values in content: name, description, url, uuid = values self.entity.log.debug("TNHypervisorRepoManager: parsing feed with url %s" % url) source_node = xmpp.Node(tag="source", attrs={"name": name, "description": description, "url": url, "uuid": uuid}) content_nodes = [] try: req = urllib2.Request(url, headers={"User-Agent": "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11", "Cache-control": "no-cache"}) f = urllib2.urlopen(req) except Exception as ex: continue try: feed_content, feed_uuid, feed_description, feed_name, items = self.getFeed(f.read()) except: tmp_cursor.execute("DELETE FROM vmcastsources WHERE url='%s'" % url) self.database_connection.commit() raise Exception('Bad format', "URL doesn't seem to contain valid VMCasts. Removed.") try: self.database_connection.execute("UPDATE vmcastsources SET uuid='%s', name='%s', description='%s' WHERE url='%s'" % (feed_uuid, feed_name, feed_description, url)) self.database_connection.commit() except Exception as ex: self.entity.log.debug("TNHypervisorRepoManager: unable to update source because: " + str(ex)) pass for item in items: name = str(item.getTag("title").getCDATA()) description = str(item.getTag("description").getCDATA()).replace("\n", "").replace("\t", "") url = str(item.getTag("enclosure").getAttr("url")) size = str(item.getTag("enclosure").getAttr("length")) pubdate = str(item.getTag("pubDate").getCDATA()) uuid = str(item.getTag("uuid").getCDATA()) status = ARCHIPEL_APPLIANCES_NOT_INSTALLED try: tmp_cursor.execute("INSERT INTO vmcastappliances VALUES (?,?,?,?,?,?,?)", (name, description, url, uuid, status, feed_uuid, '/dev/null')) self.database_connection.commit() except Exception as ex: tmp_cursor.execute("SELECT status FROM vmcastappliances WHERE uuid='%s'" % uuid) for values in tmp_cursor: status = values[0] if status == ARCHIPEL_APPLIANCES_INSTALLING and not self.download_queue.has_key(uuid): status = ARCHIPEL_APPLIANCES_INSTALLATION_ERROR new_node = xmpp.Node(tag="appliance", attrs={"name": name, "description": description, "url": url, "size": size, "date": pubdate, "uuid": uuid, "status": str(status)}) content_nodes.append(new_node) source_node.setPayload(content_nodes) nodes.append(source_node) return nodes
def _process(self): self.result = False #Offer Stream Initiation self.myAgent.DEBUG("Offer StreamInitiation to" + str(self.to)) iq = xmpp.Iq(attrs={'id': self.id}) iq.setTo(self.to) iq.setType("set") si = xmpp.Node("si", { "profile": "http://jabber.org/protocol/si/profile/spade-p2p-messaging" }) si.setNamespace("http://jabber.org/protocol/si") if self.myAgent._P2P.isReady(): p2pnode = xmpp.Node("p2p") p2pnode.setNamespace( 'http://jabber.org/protocol/si/profile/spade-p2p-messaging') p2pnode.setData(self.myAgent.getP2PUrl()) si.addChild(node=p2pnode) iq.addChild(node=si) self.myAgent.send(iq) msg = self._receive(True) if msg: self.result = False if msg.getType() == "result": self.myAgent.DEBUG("StreamRequest Agreed", "ok") try: remote_address = str( msg.getTag("si").getTag("p2p").getTag( "value").getData()) d = {"url": remote_address, "p2p": True} if str(msg.getFrom().getStripped() ) in self.myAgent._P2P.getRoutes(): self.myAgent._P2P.p2p_routes[str( msg.getFrom().getStripped())].update(d) self.result = True else: self.myAgent._P2P.p2p_routes[str( msg.getFrom().getStripped())] = d except Exception as e: self.myAgent.DEBUG( "Malformed StreamRequest Answer: " + str(e), "err") self.myAgent.P2P.p2p_routes[str( msg.getFrom().getStripped())] = {} elif msg.getType() == "error": self.myAgent.DEBUG("StreamRequest REFUSED", "warn") self.myAgent._P2P.p2p_routes[str( msg.getFrom().getStripped())] = { 'p2p': False } else: #Not message, treat like a refuse self.myAgent.DEBUG("No msg received. StreamRequest REFUSED", "warn") self.myAgent._P2P.p2p_routes[str(iq.getTo().getStripped())] = { 'p2p': False }
def get_microblog(session, user): print "[update:microblog] Getting microblog for " + user + "..." items = xmpp.Node('items', attrs={'node': 'urn:xmpp:microblog:0'}) pubsub = xmpp.Node('pubsub', attrs={'xmlns': xmpp.NS_PUBSUB}, payload=[items]) iq = xmpp.Protocol('iq', user, 'get', payload=[pubsub]) return session.SendAndCallForResponse(iq, handle_microblog)
def captchaChallenge(self): if self.engine.captcha: logger.debug("VKLogin: sending message with captcha to %s" % self.jidFrom) body = _("WARNING: VK sent captcha to you."\ " Please, go to %s and enter text from image to chat."\ " Example: !captcha my_captcha_key. Tnx") % self.engine.captcha["img"] Types = (dict(type="form"), dict(type="hidden", var="form")) msg = xmpp.Message(self.jidFrom, body, "chat", frm=TransportID) msg.setTag("x", {}, xmpp.NS_OOB) xTag = msg.getTag("x", {}, xmpp.NS_OOB) xTag.setTagData("url", self.engine.captcha["img"]) msg.setTag("captcha", {}, xmpp.NS_CAPTCHA) cTag = msg.getTag("captcha", {}, xmpp.NS_CAPTCHA) cTag.setTag("x", Types[0], xmpp.NS_DATA) imgData = vCardGetPhoto(self.engine.captcha["img"], False) imgHash = sha1(imgData).hexdigest() imgEncoded = imgData.encode("base64") cxTag = cTag.setTag("x", Types[0], xmpp.NS_DATA) cxTag.addChild("field", dict(type="hidden", var="FORM_TYPE"), [xmpp.Node("value", payload=[xmpp.NS_CAPTCHA])]) cxTag.addChild("field", dict(type="hidden", var="from"), [xmpp.Node("value", payload=[TransportID])]) cxTag.addChild("field", { "label": _("Enter shown text"), "var": "ocr" }, [ xmpp.Node("required"), xmpp.Node("media", {"xmlns": xmpp.NS_MEDIA}, [ xmpp.Node("uri", {"type": "image/jpg"}, ["cid:sha1+%[email protected]" % imgHash]) ]) ]) msg.setTag( "data", { "cid": "*****@*****.**" % imgHash, "type": "image/jpg", "max-age": "0" }, xmpp.NS_URN_OOB) obTag = msg.getTag( "data", { "cid": "*****@*****.**" % imgHash, "type": "image/jpg", "max-age": "0" }, xmpp.NS_URN_OOB) obTag.setData(imgEncoded) Sender(Component, msg) Presence = xmpp.protocol.Presence(self.jidFrom, frm=TransportID) Presence.setStatus(body) Presence.setShow("xa") Sender(Component, Presence) else: logger.error( "VKLogin: captchaChallenge called without captcha for user %s" % self.jidFrom)
def __init__(self, jid, spool=conf.profile_dir): self.spool = spool self.jid = xmpp.JID(jid).getStripped() self.file = os.path.join(self.spool, self.jid + '.cfg') if os.path.exists(self.file): fd = open(self.file) self.cfg = xmpp.Node(node=fd.read()) fd.close() else: self.cfg = xmpp.Node('options')
def calcTypeForm(self, conn, request): """ Send first form to the requesting user. """ # get the session data sessionid = request.getTagAttr('command','sessionid') session = self.sessions[sessionid] # What to do when a user sends us a response? Note, that we should always # include 'execute', as it is a default action when requester does not send # exact action to do (should be set to the same as 'next' or 'complete' fields) session['actions'] = { 'cancel': self.cancel, 'next': self.calcTypeFormAccept, 'execute': self.calcTypeFormAccept, } # The form to send calctypefield = xmpp.DataField( name='calctype', desc='Calculation Type', value=session['data']['type'], options=[ ['Calculate the diameter of a circle','circlediameter'], ['Calculate the area of a circle','circlearea'] ], typ='list-single', required=1) # We set label attribute... seems that the xmpppy.DataField cannot do that calctypefield.setAttr('label', 'Calculation Type') form = xmpp.DataForm( title='Select type of operation', data=[ 'Use the combobox to select the type of calculation you would like'\ 'to do, then click Next.', calctypefield]) # Build a reply with the form reply = request.buildReply('result') replypayload = [ xmpp.Node('actions', attrs={'execute':'next'}, payload=[xmpp.Node('next')]), form] reply.addChild( name='command', namespace=NS_COMMANDS, attrs={ 'node':request.getTagAttr('command','node'), 'sessionid':sessionid, 'status':'executing'}, payload=replypayload) self._owner.send(reply) # Question: self._owner or conn? raise xmpp.NodeProcessed
def commit_to_db(self, action, table, callback): """ Sends a command to active central agent for execution @type command: string @param command: the sql command to execute @type table: table @param command: the table of dicts of values associated with the command. """ central_agent_jid = self.central_agent_jid() if central_agent_jid: # send an iq to central agent dbCommand = xmpp.Node(tag="event", attrs={"jid": self.entity.jid}) for entry in table: entryTag = xmpp.Node(tag="entry") for key, value in entry.iteritems(): entryTag.addChild("item", attrs={ "key": key, "value": value }) dbCommand.addChild(node=entryTag) def commit_to_db_callback(conn, resp): if callback: unpacked_entries = self.unpack_entries(resp) callback(unpacked_entries) iq = xmpp.Iq(typ="set", queryNS=ARCHIPEL_NS_CENTRALAGENT, to=central_agent_jid) iq.getTag("query").addChild(name="archipel", attrs={"action": action}) iq.getTag("query").getTag("archipel").addChild(node=dbCommand) self.entity.log.debug("CENTRALDB: commit to db request %s" % iq) xmpp.dispatcher.ID += 1 iq.setID("%s-%d" % (self.entity.jid.getNode(), xmpp.dispatcher.ID)) self.entity.xmppclient.SendAndCallForResponse( iq, commit_to_db_callback) else: self.entity.log.warning( "CENTRALDB: cannot commit to db because we have not detected any central agent" )
def calcDataForm(self, conn, request, notavalue=None): """ Send a form asking for diameter. """ # get the session data sessionid = request.getTagAttr('command', 'sessionid') session = self.sessions[sessionid] # set the actions taken on requester's response session['actions'] = { 'cancel': self.cancel, 'prev': self.calcTypeForm, 'next': self.calcDataFormAccept, 'execute': self.calcDataFormAccept } # create a form radiusfield = xmpp.DataField(desc='Radius', name='radius', typ='text-single') radiusfield.setAttr('label', 'Radius') form = xmpp.DataForm( title='Enter the radius', data=[ 'Enter the radius of the circle (numbers only)', radiusfield ]) # build a reply stanza reply = request.buildReply('result') replypayload = [ xmpp.Node('actions', attrs={'execute': 'complete'}, payload=[xmpp.Node('complete'), xmpp.Node('prev')]), form ] if notavalue: replypayload.append( xmpp.Node('note', attrs={'type': 'warn'}, payload=['You have to enter valid number.'])) reply.addChild(name='command', namespace=NS_COMMANDS, attrs={ 'node': request.getTagAttr('command', 'node'), 'sessionid': request.getTagAttr('command', 'sessionid'), 'status': 'executing' }, payload=replypayload) self._owner.send(reply) raise xmpp.NodeProcessed
def captchaChallenge(self): if self.engine.captcha: logger.debug("VKLogin: sending message with captcha to %s" % self.jidFrom) body = _("WARNING: VK sent captcha to you." " Please, go to %s and enter text from image to chat." " Example: !captcha my_captcha_key. Tnx" ) % self.engine.captcha["img"] msg = xmpp.Message(self.jidFrom, body, "chat", frm=TransportID) xTag = msg.setTag("x", {}, xmpp.NS_OOB) xTag.setTagData("url", self.engine.captcha["img"]) cTag = msg.setTag("captcha", {}, xmpp.NS_CAPTCHA) imgData = vCardGetPhoto(self.engine.captcha["img"], False) if imgData: imgHash = sha1(imgData).hexdigest() imgEncoded = imgData.encode("base64") form = xmpp.DataForm("form") form.setField("FORM_TYPE", xmpp.NS_CAPTCHA, "hidden") form.setField("from", TransportID, "hidden") field = form.setField("ocr") field.setLabel(_("Enter shown text")) field.delAttr("type") field.setPayload([ xmpp.Node("required"), xmpp.Node("media", {"xmlns": xmpp.NS_MEDIA}, [ xmpp.Node("uri", {"type": "image/jpg"}, ["cid:sha1+%[email protected]" % imgHash]) ]) ]) cTag.addChild(node=form) obTag = msg.setTag( "data", { "cid": "*****@*****.**" % imgHash, "type": "image/jpg", "max-age": "0" }, xmpp.NS_URN_OOB) obTag.setData(imgEncoded) else: logger.critical( "VKLogin: can't add captcha image to message url:%s" % self.engine.captcha["img"]) Sender(Component, msg) Presence = xmpp.protocol.Presence(self.jidFrom, frm=TransportID) Presence.setStatus(body) Presence.setShow("xa") Sender(Component, Presence) else: logger.error( "VKLogin: captchaChallenge called without captcha for user %s" % self.jidFrom)
def get_geoloc(session, user): print "[update:geoloc] Getting geoloc for " + user + "..." items = xmpp.Node('items', attrs={ 'node': xmpp.NS_GEOLOC, 'max_items': '1' }) pubsub = xmpp.Node('pubsub', attrs={'xmlns': xmpp.NS_PUBSUB}, payload=[items]) iq = xmpp.Protocol('iq', user, 'get', payload=[pubsub]) return session.SendAndCallForResponse(iq, handle_geoloc)
def iq_get_appliance(self, iq): """ Get the info about an appliances according to its uuid. @type iq: xmpp.Protocol.Iq @param iq: the sender request IQ @rtype: xmpp.Protocol.Iq @return: a ready-to-send IQ containing the results """ reply = iq.buildReply("result") uuid = iq.getTag("query").getTag("archipel").getAttr("uuid") try: self.cursor.execute( "SELECT save_path, name, description FROM vmcastappliances WHERE uuid='%s'" % uuid) path, name, description = self.cursor.fetchone() node = xmpp.Node(tag="appliance", attrs={ "path": path, "name": name, "description": description }) reply.setQueryPayload([node]) except Exception as ex: reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_VMCASTS_GETAPPLIANCES) return reply
def updateGtalkStatus(self, google_username, google_pass): if '@' not in google_username: google_username = '******' % google_username print google_username #connect jid = xmpp.protocol.JID(google_username) cl = xmpp.Client(jid.getDomain(), debug=[]) if not cl.connect(('talk.google.com', 5222)): print 'Can not connect to server.' #sys.exit(1) self.updated = True return if not cl.auth(jid.getNode(), google_pass): print 'Can not auth with server %s ' % google_username self.updated = True return #build query to get current status iq = xmpp.Iq() iq.setType('get') iq.setTo(google_username) node = xmpp.Node() node.setName('query') node.setAttr('xmlns', 'google:shared-status') iq.addChild(node=node) print iq #register with server and send subscribe to status updates cl.RegisterHandler('iq', self.iqHandler) cl.send(iq) self.GoOn(cl) cl.disconnect()
def iq_get_installed_appliances(self, iq): """ Get all installed appliances. @type iq: xmpp.Protocol.Iq @param iq: the sender request IQ @rtype: xmpp.Protocol.Iq @return: a ready-to-send IQ containing the results """ reply = iq.buildReply("result") nodes = [] try: self.cursor.execute( "SELECT save_path, name, description FROM vmcastappliances WHERE status=%d" % (ARCHIPEL_APPLIANCES_INSTALLED)) for values in self.cursor: path, name, description = values node = xmpp.Node(tag="appliance", attrs={ "path": path, "name": name, "description": description }) nodes.append(node) reply.setQueryPayload(nodes) except Exception as ex: reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_VMCASTS_GETINSTALLED) return reply
def updateGtalkStatus(self): #connect jid=xmpp.protocol.JID(self.username) cl=xmpp.Client(jid.getDomain(),debug=[]) if not cl.connect(('talk.google.com',5222)): print 'Can not connect to server.' return render_to_response('gtalk/gtalk.html', { 'error': 'could not connect to server', }) if not cl.auth(jid.getNode(),self.password): print 'Can not auth with server' return render_to_response('gtalk/gtalk.html', { 'error': 'coult not auth with server', }) #build query to get current status iq = xmpp.Iq() iq.setType('get') iq.setTo(self.username) node = xmpp.Node() node.setName('query') node.setAttr('xmlns', 'google:shared-status') iq.addChild(node=node) print iq #register with server and send subscribe to status updates cl.RegisterHandler('iq',self.iqHandler) cl.send(iq) self.GoOn(cl) cl.disconnect()
def list(self): """ List virtual machines in the park. It returns a dict with the following form: [{"info": { "itemid": <PUBSUB-TICKET>, "parker": <JID-OF-PARKER>, "date": <DATE-OF-LAST-UPDATE>}, "domain": <XML-DOMAIN-NODE>}, ... ] @rtype: Array @return: listinformations about virtual machines. """ nodes = self.pubsub_vmparking.get_items() ret = [] for node in nodes: domain = xmpp.Node( node=node.getTag("virtualmachine").getTag("domain")) ret.append({ "info": { "itemid": node.getAttr("id"), "parker": node.getTag("virtualmachine").getAttr("parker"), "date": node.getTag("virtualmachine").getAttr("date") }, "domain": domain }) def sorting(a, b): return cmp(a["domain"].getTag("name").getData(), b["domain"].getTag("name").getData()) ret.sort(sorting) return ret
def iq_get_logs(self, iq): """ Read the hypervisor's log file. @type iq: xmpp.Protocol.Iq @param iq: the sender request IQ @rtype: xmpp.Protocol.Iq @return: a ready-to-send IQ containing the results """ try: reply = iq.buildReply("result") limit = int(iq.getTag("query").getTag("archipel").getAttr("limit")) output = commands.getoutput("tail -n %d %s" % (limit, self.logfile)) nodes = [] for line in output.split("\n"): try: infos = line.split("::") log_node = xmpp.Node("log", attrs={"level": infos[0], "date": infos[1], "file": "", "method": ""}) log_node.setData(line) nodes.append(log_node) except Exception as ex: pass reply.setQueryPayload(nodes) except Exception as ex: print str(ex) reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_HEALTH_LOG) return reply
def _on_centralagent_reply(vms): try: self.entity.log.debug("VMPARKING: here is the raw list result %s" % vms) reply = iq.buildReply("result") parked_vms = [] for vm in vms: try: parked_vms.append({"info": {"uuid": vm["uuid"], "parker": vm["parker"], "date": vm["creation_date"]}, "domain": xmpp.simplexml.NodeBuilder(vm["domain"]).getDom()}) except: self.entity.log.warning("VMPARKING: Error parsing entry %s" % vm) def sorting(a, b): a_name="" b_name="" if a["domain"]: a_name=a["domain"].getTag("name").getData() if b["domain"]: b_name=b["domain"].getTag("name").getData() return cmp(a_name, b_name) parked_vms.sort(sorting) nodes = [] for parked_vm in parked_vms: vm_node = xmpp.Node("virtualmachine", attrs=parked_vm["info"]) if parked_vm["domain"] and parked_vm["domain"].getTag('description'): parked_vm["domain"].delChild("description") vm_node.addChild(node=parked_vm["domain"]) nodes.append(vm_node) reply.setQueryPayload(nodes) except Exception as ex: reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_VMPARK_LIST) self.entity.xmppclient.send(reply) raise xmpp.protocol.NodeProcessed
def iq_get_names(self, iq): """ List all virtual network names. @type iq: xmpp.Protocol.Iq @param iq: the received IQ @rtype: xmpp.Protocol.Iq @return: a ready to send IQ containing the result of the action """ try: reply = iq.buildReply("result") active_networks_nodes = [] actives_networks_names = self.get(inactive=False)["active"] for network_name in actives_networks_names: network = xmpp.Node(tag="network", attrs={"name": network_name}) active_networks_nodes.append(network) reply.setQueryPayload(active_networks_nodes) except libvirt.libvirtError as ex: reply = build_error_iq(self, ex, iq, ex.get_error_code(), ns=ARCHIPEL_NS_LIBVIRT_GENERIC_ERROR) except Exception as ex: reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_NETWORKS_GETNAMES) return reply
def get_available_avatars(self, supported_file_extensions=[ "png", "jpg", "jpeg", "gif" ]): """ Return a stanza with a list of availables avatars base64 encoded. """ path = self.configuration.get("GLOBAL", "machine_avatar_directory") resp = xmpp.Node("avatars") for ctype in supported_file_extensions: for img in glob.glob(os.path.join(path, "*.%s" % ctype)): f = open(img, 'r') data = base64.b64encode(f.read()) image_hash = hashlib.md5(data).hexdigest() f.close() node_img = resp.addChild(name="avatar", attrs={ "name": img.split("/")[-1], "content-type": "image/%s" % ctype, "hash": image_hash }) node_img.setData(data) return resp
def send(self, event, users, instance, paths): if not self._ensure_connection(): print("Cannot contact the XMPP server") return for user, templates in users.items(): jid = self._get_jid(user) if not self.enabled(event, user, paths) or jid is None: continue template = self._get_template(templates) if template is None: continue params = self.prepare(template, instance) message = xmpp.protocol.Message(jid, body=params['short_description'].encode('utf-8'), subject=params['subject'].encode('utf-8'), typ='chat') html = xmpp.Node('html', {'xmlns': 'http://jabber.org/protocol/xhtml-im'}) text = u"<body xmlns='http://www.w3.org/1999/xhtml'>" + markdown2.markdown(params['short_description'], extras=["link-patterns"], link_patterns=link_registry.link_patterns( request), safe_mode=True) + u"</body>" html.addChild(node=xmpp.simplexml.XML2Node(text.encode('utf-8'))) message.addChild(node=html) self.client.send(message) self.client.disconnected()
def fetch_affiliations(self, callback=None, wait=False): """ fetch the affiliations for the node @type callback: Function @param callback: the callback function @type wait: Boolean @param wait: if true, wait for answer """ iq = xmpp.Node("iq", attrs={"type": "get", "to": self.pubsubserver}) pubsubNode = iq.addChild( "pubsub", namespace="http://jabber.org/protocol/pubsub#owner") affNode = pubsubNode.addChild("affiliations", attrs={"node": self.nodename}) def _did_fetch_affiliations(conn, resp, callback): ret = False if resp.getType() == "result": self.affiliations = {} for affiliation in resp.getTag("pubsub").getTag( "affiliations").getTags("affiliation"): self.affiliations[affiliation.getAttr( "jid")] = affiliation.getAttr("affiliation") ret = True if callback: return callback(resp) return ret if wait: resp = self.xmppclient.SendAndWaitForResponse(iq) return _did_fetch_affiliations(None, resp, callback) else: self.xmppclient.SendAndCallForResponse( iq, func=_did_fetch_affiliations, args={"callback": callback}) return True
def iq_jobs(self, iq): """ Get jobs. @type iq: xmpp.Protocol.Iq @param iq: the received IQ @rtype: xmpp.Protocol.Iq @return: a ready to send IQ containing the result of the action """ try: reply = iq.buildReply("result") nodes = [] if hasattr(self.scheduler, "get_jobs"): jobs = self.scheduler.get_jobs() else: jobs = self.scheduler.jobs for job in jobs: job_node = xmpp.Node(tag="job", attrs={ "action": str(job.args[0]), "uid": str(job.args[1]), "date": str(job.args[2]), "comment": job.args[3] }) nodes.append(job_node) reply.setQueryPayload(nodes) except Exception as ex: reply = build_error_iq(self, ex, iq) return reply
def become_central_agent(self): """ triggered when becoming active central agent """ self.is_central_agent = True self.manage_database() initial_keepalive = xmpp.Node("event", attrs={ "type": "keepalive", "jid": self.jid }) initial_keepalive.setAttr("force_update", "true") initial_keepalive.setAttr("salt", self.salt) now = datetime.datetime.now() now_string = now.strftime("%Y-%m-%d %H:%M:%S.%f") initial_keepalive.setAttr("central_agent_time", now_string) if self.required_stats_xml: initial_keepalive.addChild(node=self.required_stats_xml) self.central_keepalive_pubsub.add_item(initial_keepalive) self.log.debug("CENTRALAGENT: initial keepalive sent") self.last_keepalive_sent = datetime.datetime.now() self.last_hyp_check = datetime.datetime.now() self.change_presence("", "Active")
def iq_health_info_history(self, iq): """ Get a range of old stat history according to the limit parameters in iq node. @type iq: xmpp.Protocol.Iq @param iq: the sender request IQ @rtype: xmpp.Protocol.Iq @return: a ready-to-send IQ containing the results """ try: reply = iq.buildReply("result") self.entity.log.debug("Converting stats into XML node.") limit = int(iq.getTag("query").getTag("archipel").getAttr("limit")) nodes = [] stats = self.collector.get_collected_stats(limit) number_of_rows = limit if number_of_rows > len(stats["memory"]): number_of_rows = len(stats["memory"]) for i in range(number_of_rows): statNode = xmpp.Node("stat") statNode.addChild("memory", attrs=stats["memory"][i]) statNode.addChild("cpu", attrs=stats["cpu"][i]) statNode.addChild("disk") statNode.addChild("load", attrs=stats["load"][i]) network_node = statNode.addChild("networks") for nic, delta in json.loads(stats["network"][i]["records"]).items(): network_node.addChild("network", attrs={"name": nic, "delta": delta}) nodes.append(statNode) reply.setQueryPayload(nodes) except Exception as ex: reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_HEALTH_HISTORY) return reply
def get_vcard(session, user): print "[update:vcard] Getting vcard for " + user + "..." vcard = xmpp.Node('vCard', attrs={'xmlns': xmpp.NS_VCARD}) iq = xmpp.Protocol('iq', user, 'get', payload=[vcard]) return session.SendAndCallForResponse(iq, handle_vcard)
def iq_getgolden(self, iq): """ Get the list of golden qcow2 images @type iq: xmpp.Protocol.Iq @param iq: the received IQ @rtype: xmpp.Protocol.Iq @return: a ready to send IQ containing the result of the action """ try: nodes = [] goldens = os.listdir(self.golden_drives_dir) for golden in goldens: if self._is_file_a_qcow(os.path.join(self.golden_drives_dir, golden)) \ or self._is_file_a_qcow2(os.path.join(self.golden_drives_dir, golden)): node = xmpp.Node(tag="golden", attrs={ "name": golden, "path": os.path.join(self.golden_drives_dir, golden) }) nodes.append(node) reply = iq.buildReply("result") reply.setQueryPayload(nodes) self.entity.log.info("Info about golden sent.") except Exception as ex: reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_DRIVES_GETGOLDEN) return reply