def resultReceived(result): items = [item.attributes for item in result.query.children] if items[0].has_key('node'): for item in reversed(items): iq = IQ(client.admin.xmlstream, 'get') iq['to'] = getXMPPDomain(site) query = iq.addElement((NS_DISCO_ITEMS, 'query')) query['node'] = item['node'] iq.send().addCallbacks(resultReceived) else: subscribe_jids = [item['jid'] for item in items] if settings.admin_jid in subscribe_jids: subscribe_jids.remove(settings.admin_jid) if subscribe_jids: getJID = lambda uid: JID("%s@%s" % (escapeNode(uid), settings.xmpp_domain)) roster_jids = [ getJID(user_id.split('@')[0]) for user_id in subscribe_jids ] for member_jid in member_jids: client.chat.sendRosterItemAddSuggestion( member_jid, roster_jids, site) log.info('Roster suggestion sent for %s' % member_jid) # XXX: Somehow the last user's roster suggestions is # dropped, unless we rest here for a bit. time.sleep(3) return result
def resultReceived(result): items = [item.attributes for item in result.query.children] if 'node' in items[0]: for item in reversed(items): iq = IQ(client.admin.xmlstream, 'get') iq['to'] = settings.xmpp_domain query = iq.addElement((NS_DISCO_ITEMS, 'query')) query['node'] = item['node'] iq.send().addCallbacks(resultReceived) else: member_jids = [item['jid'] for item in items] if settings.admin_jid in member_jids: member_jids.remove(settings.admin_jid) registered_member_dicts = \ [d for d in member_dicts if d['jabberid'] in member_jids] @newzodbconnection(portal=portal) def updateVCard(): mdict = registered_member_dicts.pop() setup.setVCard(mdict, mdict['jid_obj'], mdict['pass'], updateVCard) if len(registered_member_dicts): zr = getUtility(IZopeReactor) zr.reactor.callInThread(updateVCard) return
def resultReceived(result): items = [item.attributes for item in result.query.children] if items[0].has_key('node'): for item in reversed(items): iq = IQ(client.admin.xmlstream, 'get') iq['to'] = getXMPPDomain(site) query = iq.addElement((NS_DISCO_ITEMS, 'query')) query['node'] = item['node'] iq.send().addCallbacks(resultReceived) else: subscribe_jids = [item['jid'] for item in items] if settings.admin_jid in subscribe_jids: subscribe_jids.remove(settings.admin_jid) if subscribe_jids: getJID = lambda uid: JID( "%s@%s" % (escapeNode(uid), settings.xmpp_domain)) roster_jids = [getJID(user_id.split('@')[0]) for user_id in subscribe_jids] for member_jid in member_jids: client.chat.sendRosterItemAddSuggestion(member_jid, roster_jids, site) log.info('Roster suggestion sent for %s' % member_jid) # XXX: Somehow the last user's roster suggestions is # dropped, unless we rest here for a bit. time.sleep(3) return result
def resultReceived(result): items = [item.attributes for item in result.query.children] if 'node' in items[0]: for item in reversed(items): iq = IQ(client.admin.xmlstream, 'get') iq['to'] = settings.xmpp_domain query = iq.addElement((NS_DISCO_ITEMS, 'query')) query['node'] = item['node'] iq.send().addCallbacks(resultReceived) else: member_jids = [item['jid'] for item in items] if settings.admin_jid in member_jids: member_jids.remove(settings.admin_jid) registered_member_dicts = \ [d for d in member_dicts if d['jabberid'] in member_jids] @newzodbconnection(portal=portal) def updateVCard(): mdict = registered_member_dicts.pop() setup.setVCard( mdict, mdict['jid_obj'], mdict['pass'], updateVCard) if len(registered_member_dicts): zr = getUtility(IZopeReactor) zr.reactor.callInThread(updateVCard) return
def handlePresence(self, iq): self.log_debug("Presence IQ: %s" % (iq.toXml().encode('ascii', 'replace')),) presenceType = iq.getAttribute('type') if presenceType == 'subscribe': frm = JID(iq['from']).userhost() if self.allowedInRoster(frm): self.roster[frm] = { 'debug' : False, 'available' : True } response = domish.Element(('jabber:client', 'presence')) response['to'] = iq['from'] response['type'] = 'subscribed' self.xmlStream.send(response) # request subscription as well subscribe = domish.Element(('jabber:client', 'presence')) subscribe['to'] = iq['from'] subscribe['type'] = 'subscribe' self.xmlStream.send(subscribe) else: self.log_info("JID not allowed in roster: %s" % (frm,)) # Reject response = domish.Element(('jabber:client', 'presence')) response['to'] = iq['from'] response['type'] = 'unsubscribed' self.xmlStream.send(response) elif presenceType == 'unsubscribe': frm = JID(iq['from']).userhost() if self.roster.has_key(frm): del self.roster[frm] response = domish.Element(('jabber:client', 'presence')) response['to'] = iq['from'] response['type'] = 'unsubscribed' self.xmlStream.send(response) # remove from roster as well # XXX This codepath is not unit tested removal = IQ(self.xmlStream, 'set') query = removal.addElement("query", "jabber:iq:roster") query.addElement("item") query.item["jid"] = iq["from"] query.item["subscription"] = "remove" removal.send() elif presenceType == 'unavailable': frm = JID(iq['from']).userhost() if self.roster.has_key(frm): self.roster[frm]['available'] = False else: frm = JID(iq['from']).userhost() if self.allowedInRoster(frm): if self.roster.has_key(frm): self.roster[frm]['available'] = True else: self.roster[frm] = { 'debug' : False, 'available' : True } else: self.log_info("JID not allowed in roster: %s" % (frm,))
def ping(self, entity, sender=None): """ Send out a ping request and wait for a response. @param entity: Entity to be pinged. @type entity: L{JID<twisted.words.protocols.jabber.jid.JID>} @return: A deferred that fires upon receiving a response. @rtype: L{Deferred<twisted.internet.defer.Deferred>} @param sender: Optional sender address. @type sender: L{JID<twisted.words.protocols.jabber.jid.JID>} """ def cb(response): return None def eb(failure): failure.trap(StanzaError) exc = failure.value if exc.condition == 'service-unavailable': return None else: return failure request = IQ(self.xmlstream, 'get') request.addElement((NS_PING, 'ping')) if sender is not None: request['from'] = unicode(sender) d = request.send(entity.full()) d.addCallbacks(cb, eb) return d
def modifyAffiliations(self, service, nodeIdentifier, delta): def cb(result): if result['type'] == u'result': log.info("Modified affiliations for %s: %s ." % \ (nodeIdentifier, delta)) return True return False def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return False iq = IQ(self.xmlstream, 'set') iq['to'] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, 'pubsub')) affiliations = pubsub.addElement('affiliations') affiliations['node'] = nodeIdentifier for jid, affiliation in delta: el = affiliations.addElement('affiliation') el['jid'] = jid.userhost() el['affiliation'] = affiliation d = iq.send() d.addCallbacks(cb, error) return d
def ping(self, entity, sender=None): """ Send out a ping request and wait for a response. @param entity: Entity to be pinged. @type entity: L{JID<twisted.words.protocols.jabber.jid.JID>} @return: A deferred that fires upon receiving a response. @rtype: L{Deferred<twisted.internet.defer.Deferred>} @param sender: Optional sender address. @type sender: L{JID<twisted.words.protocols.jabber.jid.JID>} """ def cb(response): return None def eb(failure): failure.trap(StanzaError) exc = failure.value if exc.condition == 'service-unavailable': return None else: return failure request = IQ(self.xmlstream, 'get') request.addElement((NS_PING, 'ping')) if sender is not None: request['from'] = sender.full() d = request.send(entity.full()) d.addCallbacks(cb, eb) return d
def modifyAffiliations(self, service, nodeIdentifier, delta): def cb(result): if result['type']==u'result': logger.info("Modified affiliations for %s: %s ." % \ (nodeIdentifier, delta)) return True return False def error(failure): # TODO: Handle gracefully? logger.error(failure.getTraceback()) return False iq = IQ(self.xmlstream, 'set') iq['to'] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, 'pubsub')) affiliations = pubsub.addElement('affiliations') affiliations['node']=nodeIdentifier for jid, affiliation in delta: el = affiliations.addElement('affiliation') el['jid'] = jid.userhost() el['affiliation'] = affiliation d = iq.send() d.addCallbacks(cb, error) return d
def getAffiliations(self, service, nodeIdentifier): def cb(result): affiliations = result.pubsub.affiliations result = [] for affiliate in affiliations.children: result.append((JID(affiliate['jid']), affiliate['affiliation'], )) logger.info("Got affiliations for %s: %s ." % \ (nodeIdentifier, result)) return result def error(failure): # TODO: Handle gracefully? logger.error(failure.getTraceback()) return [] iq = IQ(self.xmlstream, 'get') iq['to'] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, 'pubsub')) affiliations = pubsub.addElement('affiliations') affiliations['node']=nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def getNodeConfiguration(self, service, nodeIdentifier): def cb(result): fields = [field for field in result.pubsub.configure.x.children if field[u'type']!=u'hidden'] result = dict() for field in fields: value = None try: value = field.value.children[0] except (AttributeError, IndexError): pass result[field['var']] = value logger.info("Got node config %s: %s ." % (nodeIdentifier, result)) return result def error(failure): # TODO: Handle gracefully? logger.error(failure.getTraceback()) return [] iq = IQ(self.xmlstream, 'get') iq['to'] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, 'pubsub')) configure = pubsub.addElement('configure') configure['node'] = nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def getNodeConfiguration(self, service, nodeIdentifier): def cb(result): fields = [ field for field in result.pubsub.configure.x.children if field[u'type'] != u'hidden' ] result = dict() for field in fields: value = None try: value = field.value.children[0] except (AttributeError, IndexError): pass result[field['var']] = value log.info("Got node config %s: %s ." % (nodeIdentifier, result)) return result def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return [] iq = IQ(self.xmlstream, 'get') iq['to'] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, 'pubsub')) configure = pubsub.addElement('configure') configure['node'] = nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def getAffiliations(self, service, nodeIdentifier): def cb(result): affiliations = result.pubsub.affiliations result = [] for affiliate in affiliations.children: result.append(( JID(affiliate['jid']), affiliate['affiliation'], )) log.info("Got affiliations for %s: %s ." % \ (nodeIdentifier, result)) return result def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return [] iq = IQ(self.xmlstream, 'get') iq['to'] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, 'pubsub')) affiliations = pubsub.addElement('affiliations') affiliations['node'] = nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def _acceptInvitation(self, jid, url, conf): ''' Sends IQ message with <session><accept /></session> and opens window with given app @param jid: JID of user on the other side @param url: URL of app ww are invited in @param conf: configuration object ''' iq = IQ(self.main.client.xmlstream, 'set') iq['xml:lang'] = self.main.client.xmlLang iq['type'] = 'set' iq['to'] = jid + '/jabbim' q = iq.addElement('query') q['xmlns']='http://xawa.vaisar.cz' s = q.addElement('session') s.addElement('accept') s['appUrl'] = url self.main.client.disp(iq['id']) d = iq.send() ##open window with app self.openWindow() self.loadApp(url) self.loadConfiguration(conf) return d
def publishNode(self, nodeName, lock=True): if self.xmlStream is None: # We lost our connection self.unlockNode(None, nodeName) return try: if lock and not self.lockNode(nodeName): return iq = IQ(self.xmlStream) pubsubElement = iq.addElement('pubsub', defaultUri=self.pubsubNS) publishElement = pubsubElement.addElement('publish') publishElement['node'] = nodeName if self.settings["NodeConfiguration"]["pubsub#deliver_payloads"] == '1': itemElement = publishElement.addElement('item') itemElement.addElement('plistfrag', defaultUri='plist-apple') self.sendDebug("Publishing (%s)" % (nodeName,), iq) d = iq.send(to=self.settings['ServiceAddress']) d.addCallback(self.publishNodeSuccess, nodeName) d.addErrback(self.publishNodeFailure, nodeName) except: self.unlockNode(None, nodeName) raise
def sendInvite(self,jid,appInfo): ''' Sends IQ message with invitation @param jid: JID of the user on the other side @param appInfo: basic info about app ''' iq = IQ(self.main.client.xmlstream, 'set') iq['xml:lang'] = self.main.client.xmlLang iq['type'] = 'set' iq['to'] = jid + '/jabbim' q = iq.addElement('query') q['xmlns']='http://xawa.vaisar.cz' s = q.addElement('session') if (appInfo != None): s['appName'] = appInfo['appName'] s['appUrl'] = appInfo['appUrl'] s.addElement('invite') conf = s.addElement('configuration') conf.addChild(json.dumps(appInfo)) # puts whole string inside the tag self.main.client.disp(iq['id']) d = iq.send() return d
def requestRoster(self): if self.doRoster: self.roster = {} rosterIq = IQ(self.xmlStream, 'get') rosterIq.addElement("query", "jabber:iq:roster") d = rosterIq.send() d.addCallback(self.handleRoster)
def modifyAffiliations(self, service, nodeIdentifier, delta): def cb(result): if result["type"] == u"result": log.info("Modified affiliations for %s: %s ." % (nodeIdentifier, delta)) return True return False def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return False iq = IQ(self.xmlstream, "set") iq["to"] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, "pubsub")) affiliations = pubsub.addElement("affiliations") affiliations["node"] = nodeIdentifier for jid, affiliation in delta: el = affiliations.addElement("affiliation") el["jid"] = jid.userhost() el["affiliation"] = affiliation d = iq.send() d.addCallbacks(cb, error) return d
def getNodeConfiguration(self, service, nodeIdentifier): def cb(result): fields = [field for field in result.pubsub.configure.x.children if field[u"type"] != u"hidden"] result = dict() for field in fields: value = None try: value = field.value.children[0] except (AttributeError, IndexError): pass result[field["var"]] = value log.info("Got node config %s: %s ." % (nodeIdentifier, result)) return result def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return [] iq = IQ(self.xmlstream, "get") iq["to"] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, "pubsub")) configure = pubsub.addElement("configure") configure["node"] = nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def resultReceived(result): items = [item.attributes for item in result.query.children] if items[0].has_key('node'): for item in reversed(items): iq = IQ(client.admin.xmlstream, 'get') iq['to'] = settings.xmpp_domain query = iq.addElement((NS_DISCO_ITEMS, 'query')) query['node'] = item['node'] iq.send().addCallbacks(resultReceived) else: member_jids = [item['jid'] for item in items] if settings.admin_jid in member_jids: member_jids.remove(settings.admin_jid) member_ids = [item.split('@')[0] for item in member_jids] if member_ids: portal = getSite() setup.deregisterXMPPUsers(portal, member_ids) return result
def getRegisteredUsers(self, portal=None): """ XXX: This is ejabberd specific. ejabberd does not implement the #get-registered-users-list command, instead does it with an iq/get. """ iq = IQ(self.xmlstream, "get") iq["to"] = users.getXMPPDomain(portal) query = iq.addElement((NS_DISCO_ITEMS, "query")) query["node"] = "all users" d = iq.send() return d
def retrieveSubscriptions(self): # This isn't supported by Apple's pubsub service iq = IQ(self.xmlStream) pubsubElement = iq.addElement("pubsub", defaultUri=self.pubsubNS) pubsubElement.addElement("subscriptions") print("Requesting list of subscriptions") try: yield iq.send(to=self.service) except Exception, e: print("Subscription list failure: %s" % (e, ))
def getRegisteredUsers(self, portal=None): """ XXX: This is ejabberd specific. ejabberd does not implement the #get-registered-users-list command, instead does it with an iq/get. """ iq = IQ(self.xmlstream, 'get') iq['to'] = users.getXMPPDomain(portal) query = iq.addElement((NS_DISCO_ITEMS, 'query')) query['node'] = 'all users' d = iq.send() return d
def retrieveSubscriptions(self): # This isn't supported by Apple's pubsub service iq = IQ(self.xmlStream) pubsubElement = iq.addElement("pubsub", defaultUri=self.pubsubNS) pubsubElement.addElement("subscriptions") print "Requesting list of subscriptions" try: yield iq.send(to=self.service) except Exception, e: print "Subscription list failure: %s" % (e,)
def _sendPatchIQ(self, node, sender, receiver, patch): iq = IQ(self.xmlstream, 'set') iq['to'] = receiver patch = iq.addElement((NS_CE, 'patch'), content=patch) patch['node'] = node patch['user'] = sender if node in self.pending_patches: self.pending_patches[node].append(receiver) else: self.pending_patches[node] = [receiver] return iq.send()
def removeItem(self, entity): """ Remove an item from the contact list. @param entity: The contact to remove the roster item for. @type entity: L{JID<twisted.words.protocols.jabber.jid.JID>} @rtype: L{twisted.internet.defer.Deferred} """ iq = IQ(self.xmlstream, 'set') iq.addElement((NS_ROSTER, 'query')) item = iq.query.addElement('item') item['jid'] = entity.full() item['subscription'] = 'remove' return iq.send()
def unsubscribe(self, node, name, kind): iq = IQ(self.xmlStream) pubsubElement = iq.addElement("pubsub", defaultUri=self.pubsubNS) subElement = pubsubElement.addElement("unsubscribe") subElement["node"] = node subElement["jid"] = self.jid print 'Unsubscribing from "%s" (%s)' % (name, kind) if self.verbose: print node try: yield iq.send(to=self.service) print "OK" except Exception, e: print "Unsubscription failure: %s %s" % (node, e)
def unsubscribe(self, node, name, kind): iq = IQ(self.xmlStream) pubsubElement = iq.addElement("pubsub", defaultUri=self.pubsubNS) subElement = pubsubElement.addElement("unsubscribe") subElement["node"] = node subElement["jid"] = self.jid print('Unsubscribing from "%s" (%s)' % (name, kind)) if self.verbose: print(node) try: yield iq.send(to=self.service) print("OK") except Exception, e: print("Unsubscription failure: %s %s" % (node, e))
def leaveSession(self): ''' Sends IQ message width <session><leave /></session> ''' iq = IQ(self.main.client.xmlstream, 'set') iq['xml:lang'] = self.main.client.xmlLang iq['type'] = 'set' iq['to'] = self.recipient + '/jabbim' q = iq.addElement('query') q['xmlns']='http://xawa.vaisar.cz' s = q.addElement('session') s.addElement('leave') self.main.client.disp(iq['id']) d = iq.send() return d
def get_userstats(self,user,comp_name,domain): """ Get stats of user. Accepts params: user - user jid comp_name - component name which should receive answer (usually we are) domain - our domain returns callback with one cb added - it converts answer to dict with fields name,fulljid,ip,status """ def process_stats(item): """ Process result of user-stats command Extract IP address and related info and returns it as dict """ x = xpath.queryForNodes("//x/field[@var='ipaddresses']",item) if not x: raise ValueError, "Wrong response from stats-request" frm = Form.fromElement(x[0]) values = frm.getValues() jid = JID(values['accountjid']) ipport = values['ipaddresses'] ip, port = ipport.split(':') userstats = dict() userstats['username'] = jid.userhost() userstats['fulljid'] = jid.full() #full jid which causes current change, i.e. which is connestion actualy used userstats['ip'] = ip return userstats #TODO: implement error handling if ACL doesn't allows us to call admin commands iq = IQ(self.xmlstream) iq['to'] = domain iq['from'] = comp_name cmd = iq.addElement((NS_COMMANDS,'command')) cmd['node'] = CMD_ADMIN_USER_STATS frm = Form('submit') frm.addField( Field(fieldType='hidden',var='FORM_TYPE',value=NS_ADMIN) ) frm.addField( Field(fieldType='jid-single',var='accountjid',value=user.full()) ) cmd.addChild(frm.toElement()) d = iq.send(domain) d.addCallback(process_stats) return d
def publish_mood(self, mood_str, text): iq = IQ(self.xmlstream, 'set') iq['from'] = config.SCREEN_NAME pubsub = iq.addElement(('http://jabber.org/protocol/pubsub', 'pubsub')) moodpub = pubsub.addElement('publish') moodpub['node'] = 'http://jabber.org/protocol/mood' item = moodpub.addElement('item') mood = item.addElement(('http://jabber.org/protocol/mood', 'mood')) mood.addElement(mood_str) mood.addElement('text').addContent(text) def _doLog(x): log.msg("Delivered mood: %s (%s)" % (mood_str, text)) d = iq.send() d.addErrback(log.err) d.addCallback(_doLog) log.msg("Delivering mood: %s" % iq.toXml()) self.send(iq)
def createNode(self, nodeName, publish=True): if self.xmlStream is None: # We lost our connection self.unlockNode(None, nodeName) return try: iq = IQ(self.xmlStream) pubsubElement = iq.addElement('pubsub', defaultUri=self.pubsubNS) child = pubsubElement.addElement('create') child['node'] = nodeName d = iq.send(to=self.settings['ServiceAddress']) d.addCallback(self.createNodeSuccess, nodeName, publish) d.addErrback(self.createNodeFailure, nodeName, publish) except: self.unlockNode(None, nodeName) raise
def sendXawaData(self, data): ''' Sends IQ message with JSON data @param data: JSON string with data we want to send ''' iq = IQ(self.main.client.xmlstream, 'set') iq['xml:lang'] = self.main.client.xmlLang iq['type'] = 'set' iq['to'] = self.recipient + '/jabbim' q = iq.addElement('query') q['xmlns']='http://xawa.vaisar.cz' xm = q.addElement('xawaData') b = xm.addElement('data') b.addChild(data) self.main.client.disp(iq['id']) d = iq.send() return d
def _refuseInvitation(self, jid): ''' Sends IQ message with <session><refuse /></session> @param jid: JID of user of the other side ''' iq = IQ(self.main.client.xmlstream, 'set') iq['xml:lang'] = self.main.client.xmlLang iq['type'] = 'set' iq['to'] = jid + '/jabbim' q = iq.addElement('query') q['xmlns']='http://xawa.vaisar.cz' s = q.addElement('session') s.addElement('refuse') self.main.client.disp(iq['id']) d = iq.send() return d
def sendXawaMessage(self, message): ''' Sends IQ message with text message @param message: text of message we want to send ''' iq = IQ(self.main.client.xmlstream, 'set') iq['xml:lang'] = self.main.client.xmlLang iq['type'] = 'set' iq['to'] = self.recipient + '/jabbim' q = iq.addElement('query') q['xmlns']='http://xawa.vaisar.cz' xm = q.addElement('xawaMessage') b = xm.addElement('body') b.addChild(message) self.main.client.disp(iq['id']) d = iq.send() return d
def sendAnnouncement(self, body, subject="Announce"): """ Send an announement to all users. """ def resultReceived(iq): log.info("Sent announcement %s." % body) return True def formReceived(iq): command = iq.command sessionid = command["sessionid"] form = data_form.findForm(command, NODE_ADMIN) # from twisted.words.protocols.jabber.xmlstream import toResponse # response = toResponse(iq, 'set') response = IQ(self.xmlstream, "set") response["to"] = iq["from"] response["id"] = iq["id"] command = response.addElement((NS_COMMANDS, "command")) command["node"] = NODE_ADMIN_ANNOUNCE command["sessionid"] = sessionid form.formType = "submit" form.fields["subject"].value = subject form.fields["body"].value = body command.addChild(form.toElement()) d = response.send() d.addCallbacks(resultReceived, error) return d def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return False iq = IQ(self.xmlstream, "set") iq["to"] = users.getXMPPDomain() command = iq.addElement((NS_COMMANDS, "command")) command["action"] = "execute" command["node"] = NODE_ADMIN_ANNOUNCE d = iq.send() d.addCallbacks(formReceived, error) return d
def sendAnnouncement(self, body, subject='Announce'): """Send an announement to all users. """ def resultReceived(iq): logger.info("Sent announcement %s." % body) return True def formReceived(iq): command = iq.command sessionid = command['sessionid'] form = data_form.findForm(command, NODE_ADMIN) #from twisted.words.protocols.jabber.xmlstream import toResponse #response = toResponse(iq, 'set') response = IQ(self.xmlstream, 'set') response['to'] = iq['from'] response['id'] = iq['id'] command = response.addElement((NS_COMMANDS, 'command')) command['node'] = NODE_ADMIN_ANNOUNCE command['sessionid'] = sessionid form.formType = 'submit' form.fields['subject'].value = subject form.fields['body'].value = body command.addChild(form.toElement()) d = response.send() d.addCallbacks(resultReceived, error) return d def error(failure): # TODO: Handle gracefully? logger.error(failure.getTraceback()) return False iq = IQ(self.xmlstream, 'set') iq['to'] = self.xmlstream.factory.authenticator.jid.host command = iq.addElement((NS_COMMANDS, 'command')) command['action'] = 'execute' command['node'] = NODE_ADMIN_ANNOUNCE d = iq.send() d.addCallbacks(formReceived, error) return d
def getNodeType(self, service, nodeIdentifier): def cb(result): result = result.query.identity["type"] log.info("Got node type %s: %s ." % (nodeIdentifier, result)) return result def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return [] iq = IQ(self.xmlstream, "get") iq["to"] = service.full() query = iq.addElement((NS_DISCO_INFO, "query")) query["node"] = nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def getNodeType(self, service, nodeIdentifier): def cb(result): result = result.query.identity['type'] log.info("Got node type %s: %s ." % (nodeIdentifier, result)) return result def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return [] iq = IQ(self.xmlstream, 'get') iq['to'] = service.full() query = iq.addElement((NS_DISCO_INFO, 'query')) query['node'] = nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def sendAnnouncement(self, body, subject='Announce'): """ Send an announement to all users. """ def resultReceived(iq): log.info("Sent announcement %s." % body) return True def formReceived(iq): command = iq.command sessionid = command['sessionid'] form = data_form.findForm(command, NODE_ADMIN) #from twisted.words.protocols.jabber.xmlstream import toResponse #response = toResponse(iq, 'set') response = IQ(self.xmlstream, 'set') response['to'] = iq['from'] response['id'] = iq['id'] command = response.addElement((NS_COMMANDS, 'command')) command['node'] = NODE_ADMIN_ANNOUNCE command['sessionid'] = sessionid form.formType = 'submit' form.fields['subject'].value = subject form.fields['body'].value = body command.addChild(form.toElement()) d = response.send() d.addCallbacks(resultReceived, error) return d def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return False iq = IQ(self.xmlstream, 'set') iq['to'] = users.getXMPPDomain() command = iq.addElement((NS_COMMANDS, 'command')) command['action'] = 'execute' command['node'] = NODE_ADMIN_ANNOUNCE d = iq.send() d.addCallbacks(formReceived, error) return d
def addUser(self, userjid, password): """ Add a user """ def resultReceived(iq): log.info("Added user %s" % userjid) return True def formReceived(iq): command = iq.command sessionid = command["sessionid"] form = data_form.findForm(command, NODE_ADMIN) response = IQ(self.xmlstream, "set") response["to"] = iq["from"] response["id"] = iq["id"] command = response.addElement((NS_COMMANDS, "command")) command["node"] = NODE_ADMIN_ADD_USER command["sessionid"] = sessionid form.formType = "submit" form.fields["accountjid"].value = userjid form.fields["password"].value = password form.fields["password-verify"].value = password command.addChild(form.toElement()) d = response.send() d.addCallbacks(resultReceived, error) return d def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return False iq = IQ(self.xmlstream, "set") iq["to"] = users.getXMPPDomain() command = iq.addElement((NS_COMMANDS, "command")) command["action"] = "execute" command["node"] = NODE_ADMIN_ADD_USER d = iq.send() d.addCallbacks(formReceived, error) return d
def addUser(self, userjid, password): """ Add a user """ def resultReceived(iq): log.info("Added user %s" % userjid) return True def formReceived(iq): command = iq.command sessionid = command['sessionid'] form = data_form.findForm(command, NODE_ADMIN) response = IQ(self.xmlstream, 'set') response['to'] = iq['from'] response['id'] = iq['id'] command = response.addElement((NS_COMMANDS, 'command')) command['node'] = NODE_ADMIN_ADD_USER command['sessionid'] = sessionid form.formType = 'submit' form.fields['accountjid'].value = userjid form.fields['password'].value = password form.fields['password-verify'].value = password command.addChild(form.toElement()) d = response.send() d.addCallbacks(resultReceived, error) return d def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return False iq = IQ(self.xmlstream, 'set') iq['to'] = users.getXMPPDomain() command = iq.addElement((NS_COMMANDS, 'command')) command['action'] = 'execute' command['node'] = NODE_ADMIN_ADD_USER d = iq.send() d.addCallbacks(formReceived, error) return d
def deleteUsers(self, userjids): """ """ def resultReceived(iq): log.info("Deleted users %s" % userjids) return True def formReceived(iq): command = iq.command sessionid = command['sessionid'] form = data_form.findForm(command, NODE_ADMIN) response = IQ(self.xmlstream, 'set') response['to'] = iq['from'] response['id'] = iq['id'] command = response.addElement((NS_COMMANDS, 'command')) command['node'] = NODE_ADMIN_DELETE_USER command['sessionid'] = sessionid form.formType = 'submit' form.fields['accountjids'].values = userjids command.addChild(form.toElement()) d = response.send() d.addCallbacks(resultReceived, error) return d def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return False if isinstance(userjids, basestring): userjids = [userjids] iq = IQ(self.xmlstream, 'set') iq['to'] = users.getXMPPDomain() command = iq.addElement((NS_COMMANDS, 'command')) command['action'] = 'execute' command['node'] = NODE_ADMIN_DELETE_USER d = iq.send() d.addCallbacks(formReceived, error) return d
def formReceived(iq): command = iq.command sessionid = command['sessionid'] form = data_form.findForm(command, NODE_ADMIN) response = IQ(self.xmlstream, 'set') response['to'] = iq['from'] response['id'] = iq['id'] command = response.addElement((NS_COMMANDS, 'command')) command['node'] = NODE_ADMIN_DELETE_USER command['sessionid'] = sessionid form.formType = 'submit' form.fields['accountjids'].values = userjids command.addChild(form.toElement()) d = response.send() d.addCallbacks(resultReceived, error) return d
def getNodes(self, service, nodeIdentifier=None): def cb(result): items = result.query.children result = [item.attributes for item in items] log.info("Got nodes of %s: %s ." % (nodeIdentifier, result)) return result def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return [] iq = IQ(self.xmlstream, 'get') iq['to'] = service.full() query = iq.addElement((NS_DISCO_ITEMS, 'query')) if nodeIdentifier is not None: query['node'] = nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def getRoster(self): """ Retrieve contact list. @return: Roster as a mapping from L{JID} to L{RosterItem}. @rtype: L{twisted.internet.defer.Deferred} """ def processRoster(result): roster = {} for element in domish.generateElementsQNamed( result.query.children, 'item', NS_ROSTER): item = self._parseRosterItem(element) roster[item.jid.userhost()] = item return roster iq = IQ(self.xmlstream, 'get') iq.addElement((NS_ROSTER, 'query')) d = iq.send() d.addCallback(processRoster) return d
def configureNode(self, service, nodeIdentifier, options): def cb(result): log.info("Configured %s: %s ." % (nodeIdentifier, options)) return True def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return False form = data_form.Form(formType='submit', formNamespace=NS_PUBSUB_NODE_CONFIG) form.makeFields(options) iq = IQ(self.xmlstream, 'set') iq['to'] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, 'pubsub')) configure = pubsub.addElement('configure') configure['node'] = nodeIdentifier configure = configure.addChild(form.toElement()) d = iq.send() d.addCallbacks(cb, error) return d
def associateNodeWithCollection(self, service, nodeIdentifier, collectionIdentifier): """ XXX: Not supported by ejabberd """ def cb(result): return True def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return False iq = IQ(self.xmlstream, 'set') iq['to'] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, 'pubsub')) collection = pubsub.addElement('collection') collection['node'] = collectionIdentifier associate = collection.addElement('associate') associate['node'] = nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def getSubscriptions(self, service, nodeIdentifier): def cb(result): subscriptions = result.pubsub.subscriptions.children result = [(JID(item['jid']), item['subscription']) for item in subscriptions] log.info("Got subscriptions for %s: %s ." % \ (nodeIdentifier, result)) return result def error(failure): # TODO: Handle gracefully? log.error(failure.getTraceback()) return [] iq = IQ(self.xmlstream, 'get') iq['to'] = service.full() pubsub = iq.addElement((NS_PUBSUB_OWNER, 'pubsub')) subscriptions = pubsub.addElement('subscriptions') subscriptions['node'] = nodeIdentifier d = iq.send() d.addCallbacks(cb, error) return d
def publish_mood(self, mood_str, text): iq = IQ(self.xmlstream, 'set') iq['from'] = self.jid pubsub = iq.addElement(('http://jabber.org/protocol/pubsub', 'pubsub')) moodpub = pubsub.addElement('publish') moodpub['node'] = 'http://jabber.org/protocol/mood' item = moodpub.addElement('item') mood = item.addElement(('http://jabber.org/protocol/mood', 'mood')) mood.addElement(mood_str) mood.addElement('text').addContent(text) def _doLog(x): log.msg("Delivered mood: %s (%s)" % (mood_str, text)) def _hasError(x): log.err(x) log.msg("Error delivering mood, disabling for %s." % self.jid) self.pubsub = False log.msg("Delivering mood: %s" % iq.toXml()) d = iq.send() d.addCallback(_doLog) d.addErrback(_hasError)
def formReceived(iq): command = iq.command sessionid = command['sessionid'] form = data_form.findForm(command, NODE_ADMIN) #from twisted.words.protocols.jabber.xmlstream import toResponse #response = toResponse(iq, 'set') response = IQ(self.xmlstream, 'set') response['to'] = iq['from'] response['id'] = iq['id'] command = response.addElement((NS_COMMANDS, 'command')) command['node'] = NODE_ADMIN_ANNOUNCE command['sessionid'] = sessionid form.formType = 'submit' form.fields['subject'].value = subject form.fields['body'].value = body command.addChild(form.toElement()) d = response.send() d.addCallbacks(resultReceived, error) return d
def getVersion(xmlstream): iq = IQ(xmlstream, 'get') iq.addElement((NS_VERSION, 'query')) d = iq.send('localhost') return d