def test_modifyAffiliations(self): d = self.protocol.modifyAffiliations( JID(u'pubsub.example.com'), u'foo_node', [(JID(u'*****@*****.**'), 'none')]) iq = self.stub.output[-1] self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to')) self.assertEqual(u'set', iq.getAttribute(u'type')) self.failIf(iq.pubsub is None) self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri) self.failIf(iq.pubsub.affiliations is None) self.assertEqual('foo_node', iq.pubsub.affiliations['node']) affiliation = iq.pubsub.affiliations.affiliation self.assertEqual('*****@*****.**', affiliation['jid']) self.assertEqual('none', affiliation['affiliation']) response = toResponse(iq, u'result') response['to'] = \ self.protocol.xmlstream.factory.authenticator.jid.full() self.stub.send(response) def cb(result): self.assertEqual(result, True) d.addCallback(cb) return d
def test_infoNotDeferred(self): """ C{info} should gather disco info from sibling handlers. """ discoItems = [ disco.DiscoIdentity('dummy', 'generic', 'Generic Dummy Entity'), disco.DiscoFeature('jabber:iq:version') ] class DiscoResponder(XMPPHandler): implements(disco.IDisco) def getDiscoInfo(self, requestor, target, nodeIdentifier): if not nodeIdentifier: return discoItems else: return [] def cb(result): self.assertEquals(discoItems, result) self.service.parent = [self.service, DiscoResponder()] d = self.service.info(JID('*****@*****.**'), JID('example.com'), '') d.addCallback(cb) return d
def test_setSubscriptions(self): d = self.protocol.setSubscriptions( JID(u'pubsub.example.com'), u'foo_node', [(JID(u'*****@*****.**'), u'subscribed'), (JID(u'*****@*****.**'), u'none')]) iq = self.stub.output[-1] self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to')) self.assertEqual(u'set', iq.getAttribute(u'type')) self.failIf(iq.pubsub is None) self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri) self.failIf(iq.pubsub.subscriptions is None) self.assertEqual(u'foo_node', iq.pubsub.subscriptions.getAttribute(u'node')) subscriptions = iq.pubsub.subscriptions.children self.assertEqual(2, len(subscriptions)) self.assertEqual(u'*****@*****.**', subscriptions[0]['jid']) self.assertEqual(u'subscribed', subscriptions[0]['subscription']) self.assertEqual(u'*****@*****.**', subscriptions[1]['jid']) self.assertEqual(u'none', subscriptions[1]['subscription']) response = toResponse(iq, u'result') response['to'] = \ self.protocol.xmlstream.factory.authenticator.jid.full() self.stub.send(response) def cb(result): self.assertEqual(True, result) d.addCallback(cb) return d
def items(requestor, service, nodeIdentifier, maxItems, items): self.assertEqual(JID('*****@*****.**'), requestor) self.assertEqual(JID('pubsub.example.org'), service) self.assertEqual('test', nodeIdentifier) self.assertIdentical(None, maxItems) self.assertEqual([], items) return defer.succeed([pubsub.Item('current')])
def test_subscribe(self): """ Test sending subscription request. """ d = self.protocol.subscribe(JID('pubsub.example.org'), 'test', JID('*****@*****.**')) iq = self.stub.output[-1] self.assertEquals('pubsub.example.org', iq.getAttribute('to')) self.assertEquals('set', iq.getAttribute('type')) self.assertEquals('pubsub', iq.pubsub.name) self.assertEquals(NS_PUBSUB, iq.pubsub.uri) children = list( domish.generateElementsQNamed(iq.pubsub.children, 'subscribe', NS_PUBSUB)) self.assertEquals(1, len(children)) child = children[0] self.assertEquals('test', child['node']) self.assertEquals('*****@*****.**', child['jid']) response = toResponse(iq, 'result') pubsub = response.addElement((NS_PUBSUB, 'pubsub')) subscription = pubsub.addElement('subscription') subscription['node'] = 'test' subscription['jid'] = '*****@*****.**' subscription['subscription'] = 'subscribed' self.stub.send(response) return d
def _set_status(self, u, status, cb): # If we've got them on the preferred service, unsubscribe them # from this one. if not self.preferred and (u.service_jid and u.service_jid != self.jid): log.msg("Unsubscribing %s from non-preferred service %s" % (u.jid, self.jid)) self.unsubscribe(JID(u.jid)) self.unsubscribed(JID(u.jid)) return modified = False j = self.jid if (not u.service_jid) or (self.preferred and u.service_jid != j): u.service_jid = j modified = True if u.status != status: u.status = status modified = True global service_mapping service_mapping[u.jid] = u.service_jid log.msg("Service mapping for %s is %s" % (u.jid, u.service_jid)) if modified: if cb: cb() return u.save()
def makeService(self, options): """ Make services to handle push event notifications. """ # check confguration file is specified and exists if not options["config"]: raise ValueError( 'Configuration file not specified (try to check --help option)' ) cfgFileName = options["config"] if not os.path.isfile(cfgFileName): raise ValueError('Configuration file not found:', cfgFileName) # read configuration file cfg = ConfigParser() cfg.read(cfgFileName) # create Twisted application application = service.Application("gitlab-webhook-xmpp") serviceCollection = service.IServiceCollection(application) # create XMPP client client = XMPPClient(JID(cfg.get('xmpp', 'jid')), cfg.get('xmpp', 'password')) # client.logTraffic = True client.setServiceParent(application) # join to all MUC rooms nickname = cfg.get('xmpp', 'nickname') if cfg.has_option( 'xmpp', 'nickname') else DEFAULT_NICKNAME notifications = cfg.items('notifications') for room, repositoryMasks in notifications: mucHandler = MUCHandler(JID(room), nickname, repositoryMasks.split(',')) mucHandler.setHandlerParent(client) self.mucHandlers.append(mucHandler) templateLoader = None if cfg.has_option('message', 'template'): templateFullName = cfg.get('message', 'template') templatePath, self.templateName = os.path.split(templateFullName) templateLoader = FileSystemLoader(templatePath) else: self.templateName = DEFAULT_TEMPLATE_NAME templateLoader = PackageLoader('xmpp_webhook', 'templates') self.templateEnvironment = Environment(loader=templateLoader, extensions=['jinja2.ext.i18n']) self.templateEnvironment.install_null_translations( ) # use i18n to pluralize only # create web hook handler rootHttpResource = Resource() rootHttpResource.putChild('', WebHookHandler(self)) site = server.Site(rootHttpResource) httpPort = cfg.getint('http', 'port') if cfg.has_option( 'http', 'port') else DEFAULT_HTTP_PORT httpServer = internet.TCPServer(httpPort, site) httpServer.setServiceParent(serviceCollection) return serviceCollection
def test_jidWhenInitialized(self): """ Make sure that upon login, the JID is updated from the authenticator. """ xs = self.client.factory.buildProtocol(None) self.client.factory.authenticator.jid = JID('[email protected]/test') xs.dispatch(xs, xmlstream.STREAM_AUTHD_EVENT) self.assertEquals(JID('[email protected]/test'), self.client.jid)
def test_getVersion(self): to = 'to' self.CV.getVersion(jid=to) result = self.CV.dispatcher.data[0] self.assertEqual(result.type_, 'get') self.assertEqual(result.to, JID(to)) self.assertEqual(result.from_, JID('jid')) self.assertTrue(isinstance(result, Iq))
def items(requestor, target, nodeIdentifier): self.assertEqual(JID('*****@*****.**'), requestor) self.assertEqual(JID('example.com'), target) self.assertEqual('', nodeIdentifier) return defer.succeed([ disco.DiscoItem(JID('example.com'), 'test', 'Test node'), ])
def test_getInfo(self): result = self.disco.getInfo(self.to) self.assertTrue(isinstance(result, Deferred)) result = self.disco.dispatcher.data[0] self.assertEqual(result.type_, 'get') self.assertEqual(result.to, JID(self.to)) self.assertEqual(result.from_, JID('myjid')) self.assertTrue(isinstance(result, Iq))
def test_init(self): """ Test initialization with a category, type and name. """ item = disco.DiscoItem(JID(u'example.org'), u'test', u'The node') self.assertEqual(JID(u'example.org'), item.entity) self.assertEqual(u'test', item.nodeIdentifier) self.assertEqual(u'The node', item.name)
def test_toElementRecipient(self): """ A request without recipient, has no 'to' attribute. """ self.request = generic.Request(recipient=JID('*****@*****.**')) self.assertEquals(JID('*****@*****.**'), self.request.recipient) element = self.request.toElement() self.assertEquals(u'*****@*****.**', element.getAttribute('to'))
def test_probeSender(self): """ It should be possible to pass a sender address. """ self.protocol.probe(JID('*****@*****.**'), sender=JID('*****@*****.**')) element = self.output[-1] self.assertEquals("*****@*****.**", element.getAttribute('from'))
def test_toElementSender(self): """ A request with sender, has a 'from' attribute. """ self.request = generic.Request(sender=JID('*****@*****.**')) self.assertEquals(JID('*****@*****.**'), self.request.sender) element = self.request.toElement() self.assertEquals(u'*****@*****.**', element.getAttribute('from'))
def getConfiguration(requestor, service, nodeIdentifier): self.assertEqual(JID('*****@*****.**'), requestor) self.assertEqual(JID('pubsub.example.org'), service) self.assertEqual('test', nodeIdentifier) return defer.succeed({ 'pubsub#deliver_payloads': '0', 'pubsub#persist_items': '1' })
def test_fromElement(self): xml = """ <message type='chat' from='*****@*****.**' to='*****@*****.**'/> """ stanza = generic.Stanza.fromElement(generic.parseXml(xml)) self.assertEqual('chat', stanza.stanzaType) self.assertEqual(JID('*****@*****.**'), stanza.sender) self.assertEqual(JID('*****@*****.**'), stanza.recipient)
def setConfiguration(requestor, service, nodeIdentifier, options): self.assertEqual(JID('*****@*****.**'), requestor) self.assertEqual(JID('pubsub.example.org'), service) self.assertEqual('test', nodeIdentifier) self.assertEqual( { 'pubsub#deliver_payloads': False, 'pubsub#persist_items': True }, options) return defer.succeed(None)
def _onPresenceUnavailable(self, presence): entity = JID(presence["from"]) statuses = self._getStatuses(presence) realjid = None if presence.x and presence.x.defaultUri == 'http://jabber.org/protocol/muc#user' and presence.x.item.hasAttribute('jid'): realjid = JID(presence.x.item["jid"]) self.unavailableReceived(entity, statuses, realjid)
def info(requestor, target, nodeIdentifier): self.assertEqual(JID('*****@*****.**'), requestor) self.assertEqual(JID('example.com'), target) self.assertEqual('', nodeIdentifier) return defer.succeed([ disco.DiscoIdentity('dummy', 'generic', 'Generic Dummy Entity'), disco.DiscoFeature('jabber:iq:version') ])
def test_jidDeprecationSet(self): """ Setting the jid attribute works as entity and warns deprecation. """ item = xmppim.RosterItem(JID('*****@*****.**')) self.assertWarns( DeprecationWarning, "wokkel.xmppim.RosterItem.jid was deprecated " "in Wokkel 0.7.1; " "please use RosterItem.entity instead.", xmppim.__file__, setattr, item, 'jid', JID('*****@*****.**')) self.assertEqual(JID('*****@*****.**'), item.entity)
def testSetUp(self): client = getUtility(IAdminClient) if client._state == 'disconnected': zr = getUtility(IZopeReactor) zr.reactor.callFromThread(client.connect) wait_for_client_state(client, 'authenticated') _setupXMPPEnvironment( client, member_jids=[JID('test_user_1_@localhost')], member_passwords={JID('test_user_1_@localhost'): 'secret'}) wait_on_client_deferreds(client)
def test_getDiscoItems(self): """ Items are not supported by this handler, so an empty list is expected. """ def cb(items): self.assertEquals(0, len(items)) d = defer.maybeDeferred(self.protocol.getDiscoItems, JID('[email protected]/home'), JID('pubsub.example.org'), '') d.addCallback(cb) return d
def setUp(self): self.stub = XmlStreamStub() self.protocol = muc.MUCClient() self.protocol.xmlstream = self.stub.xmlstream self.protocol.connectionInitialized() self.test_room = 'test' self.test_srv = 'conference.example.org' self.test_nick = 'Nick' self.room_jid = JID(self.test_room + '@' + self.test_srv + '/' + self.test_nick) self.user_jid = JID('[email protected]/Testing')
def __init__(self, context, request): super(BrowserView, self).__init__(context, request) self.jid = request.get('jid') self.user_id = JID(self.jid).user self.bare_jid = JID(self.jid).userhost() self.pm = getToolByName(context, 'portal_membership') info = self.pm.getMemberInfo(self.user_id) if info: self._fullname = info.get('fullname') or self.user_id self._portrait_url = self.pm.getPersonalPortrait(self.user_id).absolute_url() else: self._fullname = '' self._portrait_url = ''
def updateBalance(self, jid): client = database.getSMS77Client(JID(jid)) if client != None: balance = client.getBalance() if balance != None: status = { None: "Kontostand EUR " + balance, "de": "Kontostand EUR " + balance, "en": "account balance EUR " + balance } if balance != database.getBalance(JID(jid)): self.send(AvailablePresence(JID(jid), None, status, 0)) database.setBalance(JID(jid), balance)
def test_pingWithSender(self): """ Pinging a service with a sender address should include that address. """ d = self.protocol.ping(JID("example.com"), sender=JID('*****@*****.**')) iq = self.stub.output[-1] self.assertEqual(u'*****@*****.**', iq.getAttribute(u'from')) response = toResponse(iq, u'result') self.stub.send(response) return d
def __init__(self, jid, jdomain, password, pubsub_jid): jid = JID(jid) self.pubsub_jid = JID(pubsub_jid) self.admin = AdminHandler() self.pubsub = PubSubHandler() self.chat = ChatHandler() self.presence = PresenceClientProtocol() super(AdminClient, self).__init__( jid, password, extra_handlers=[self.admin, self.pubsub, self.chat, self.presence], host=jdomain)
def test_getDiscoInfoNode(self): """ The ping namespace should not be returned for a node. """ def cb(info): discoInfo = disco.DiscoInfo() for item in info: discoInfo.append(item) self.assertNotIn('urn:xmpp:ping', discoInfo.features) d = defer.maybeDeferred(self.protocol.getDiscoInfo, JID('[email protected]/home'), JID('pubsub.example.org'), 'test') d.addCallback(cb) return d
def test_fromElement(self): xml = """<presence from='*****@*****.**' to='*****@*****.**'> <show>chat</show> <status>Let's chat!</status> <priority>50</priority> </presence> """ presence = xmppim.AvailabilityPresence.fromElement(parseXml(xml)) self.assertEquals(JID('*****@*****.**'), presence.sender) self.assertEquals(JID('*****@*****.**'), presence.recipient) self.assertTrue(presence.available) self.assertEquals('chat', presence.show) self.assertEquals({None: "Let's chat!"}, presence.statuses) self.assertEquals(50, presence.priority)