Example #1
0
 def call_msg_handlers(self, t, s, b, subject, stanza):
     if t == 'error': return
     if subject:
         j = JID(s)
         if not j.userhost() in self.g.keys():
             self.log.log(
                 'ignored subject from %s, stanza was %s' %
                 (escape(s), escape(stanza.toXml())), 3)
         else:
             self.log.log(
                 'got subject from %s, stanza was %s, let\'s call topichandlers'
                 % (escape(s), escape(stanza.toXml())), 1)
             if j.resource:
                 for i in self.topichandlers:
                     self.call(i, s, subject)
             else:
                 for i in self.topichandlers:
                     self.call(i, s, b)
     else:
         delayed = [
             i for i in stanza.children
             if (i.__class__ == domish.Element) and (
                 (i.name == 'delay') or (
                     (i.name == 'x') and (i.uri == 'jabber:x:delay')))
         ]
         if delayed: dl = True
         else: dl = False
         for i in self.msghandlers:
             if (t == 'groupchat') or not i[1]: self.call(i[0], s, b, dl)
Example #2
0
    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
Example #3
0
    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
Example #4
0
    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()
Example #5
0
 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')])
Example #6
0
    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
Example #7
0
    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
Example #8
0
    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
Example #9
0
 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'))
Example #10
0
 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))
Example #11
0
 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))
Example #12
0
        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'),
            ])
Example #13
0
 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)
Example #14
0
 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)
Example #15
0
 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'))
Example #16
0
 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'))
Example #17
0
 def test_bosh_authentication(self):
     jid = JID('admin@localhost')
     jid.resource = str(random.randint(0, 1000))
     client = BOSHClient(jid, 'admin', 'http://localhost:5280/http-bind/')
     self.assertTrue(client.startSession())
     rid = client.rid
     sid = client.sid
     self.assertTrue(rid is not None)
     self.assertTrue(sid is not None)
Example #18
0
 def __call__(self, user, prot, args):
     # For bare jids, we'll send what was requested,
     # but also look up the user and send it to any active resources
     self.ping(prot, user.jid, args)
     j = JID(args)
     if j.user and not j.resource:
         for rsrc in scheduling.resources(args):
             j.resource=rsrc
             self.ping(prot, user.jid, j.full())
Example #19
0
	def sendMessage(self, recipient: JID, sender: JID, text: str, messageType: str = "chat"):
		el = Element((None, "message"))
		el.attributes["to"] = recipient.full()
		el.attributes["from"] = sender.full()
		el.attributes["type"] = messageType

		body = el.addElement("body")
		body.addContent(escape(text))
		self.send(el)
Example #20
0
 def test_bosh_authentication(self):
     jid = JID('admin@localhost')
     jid.resource = str(random.randint(0, 1000))
     client = BOSHClient(jid, 'admin', 'http://localhost:5280/http-bind/')
     self.assertTrue(client.startSession())
     rid = client.rid
     sid = client.sid
     self.assertTrue(rid is not None)
     self.assertTrue(sid is not None)
Example #21
0
    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)
Example #22
0
 def get_user(self, msg, session):
     jid = JID(msg['from'])
     try:
         rv = models.User.by_jid(jid.userhost(), session)
     except:
         print "Getting user without the jid in the DB (%s)" % jid.full()
         rv = models.User.update_status(jid.userhost(), None, session)
         self.subscribe(jid)
     return rv
Example #23
0
        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'
            })
Example #24
0
 def get_user(self, msg, session):
     jid = JID(msg['from'])
     try:
         user = models.User.by_jid(jid.userhost(), session)
     except:
         log.msg("Getting user without the jid in the DB (%s)" % jid.full())
         user = models.User.update_status(jid.userhost(), None, session)
         self.subscribe(jid)
     return user;
Example #25
0
 def get_user(self, msg, session):
     jid = JID(msg["from"])
     try:
         rv = models.User.by_jid(jid.userhost(), session)
     except:
         print "Getting user without the jid in the DB (%s)" % jid.full()
         rv = models.User.update_status(jid.userhost(), None, session)
         self.subscribe(jid)
     return rv
Example #26
0
 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)
Example #27
0
    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)
Example #28
0
File: data.py Project: srothan/io
    def _cb_subscribe_default_users (self, r, ) :
        _dl = list()
        for i in constant.LDAP_USERS :
            _jid = JID("%s@%s" % (i, self.parent.jid.host, ), )
            if _jid.userhost() == self.parent.jid.userhost() or _jid.userhost() in r :
                continue

            _dl.append(defer.maybeDeferred(self.subscribe, _jid, ), )

        return defer.DeferredList(_dl, )
Example #29
0
        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')
            ])
Example #30
0
 def __init__(self, context, request):
     super(MUCView, self).__init__(context, request)
     room = request.get('room', None)
     self.invitee = request.get('invitee', None)
     if room is not None:
         self.room_jid = JID(room)
     else:
         room = random.randint(0, 4294967295)
         registry = getUtility(IRegistry)
         self.room_jid = JID(registry['jarn.xmpp.conferenceJID'])
         self.room_jid.user = room
Example #31
0
 def call_msg_handlers(self, t, s, b, subject, stanza):
  if subject:
   j = JID(s)
   if not j.userhost() in self.g.keys():
    self.log.log('ignored subject from %s, stanza was %s' % (escape(s), escape(stanza.toXml())), 3)
   else:
    self.log.log('got subject from %s, stanza was %s, let\'s call topichandlers' % (escape(s), escape(stanza.toXml())), 1)
    for i in self.topichandlers: self.call(i, s, subject)
  else:
   for i in self.msghandlers:
    if (t == 'groupchat') or not i[1]: self.call(i[0], s, b)
Example #32
0
 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)
Example #33
0
 def __getVersion(self, sender: JID, recipient: JID, identifier: str):
     iq = Element((None, "iq"))
     iq.attributes["type"] = "result"
     iq.attributes["from"] = recipient.full()
     iq.attributes["to"] = sender.full()
     if identifier:
         iq.attributes["id"] = identifier
     query = iq.addElement("query")
     query.attributes["xmlns"] = "jabber:iq:version"
     query.addElement("name", content="h2x transport")
     query.addElement("version", content=0)
     self.h2x.send(iq)
Example #34
0
    def get_forward_jids(self, stanza):
        entity_from = JID(stanza["from"])
        entity_to = JID(stanza["to"])

        if entity_from.userhost() == self.jid_proxy_to:
            new_jid_to = self.untranslate_jid(entity_to.full())
            new_jid_from = self.jid_act_as
        else:
            new_jid_to = self.jid_proxy_to
            new_jid_from = self.translate_jid(entity_from.full())

        return new_jid_to, new_jid_from
Example #35
0
    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')
Example #36
0
    def doProbe(self, account):
        if isinstance(account, str):
            account = JID(account)
        d = Deferred()

        from twisted.internet import reactor
        reactor.callLater(self.RECIEVE_FOR_SECS,
                          self.sendResults,
                          account.userhost())
        self.statusJobs[account.userhost()] = self.StatusJobState(d)
        self.probe(account)
        return d
Example #37
0
    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
Example #38
0
    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)
Example #39
0
def failure(msg):
    _from = JID(msg['from'])
    bare_from = _from.userhost()
    user = (yield objs.User.find_one({'jid': bare_from}))  # only active jid
    if not user:
        return
    if msg.error:
        if msg.error.getAttribute('code') == '500' and msg.error.__getattr__('resource-constraint'):
            print 'User %s automatically set off because his offline storage is full.' % (user['name'],)
            objs.User.mupdate({'name': user['name']}, {'$set': {'off': True}})
            return
    print 'Unknown delivery failure'
Example #40
0
 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 = ''
Example #41
0
    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')
Example #42
0
    def __getDiscoInfo(self, sender: JID, identifier: str, node: str):
        iq = Element((None, "iq"))
        iq.attributes["type"] = "result"
        iq.attributes["from"] = self.h2x.config.JID
        iq.attributes["to"] = sender.full()
        if identifier:
            iq.attributes["id"] = identifier
        query = iq.addElement("query")
        query.attributes["xmlns"] = "http://jabber.org/protocol/disco#info"

        # Node not set -> send component identity
        if node == None:
            identity = query.addElement("identity")
            identity.attributes["name"] = "Google Hangouts transport"
            identity.attributes["category"] = "gateway"
            identity.attributes["type"] = "XMPP"
            query.addElement("feature").attributes["var"] = "jabber:iq:gateway"
            query.addElement("feature").attributes["var"] = "jabber:iq:register"
            query.addElement("feature").attributes["var"] = "jabber:iq:version"

            # Generic features for both node and component
        query.addElement("feature").attributes["var"] = "http://jabber.org/protocol/commands"
        query.addElement("feature").attributes["var"] = "http://jabber.org/protocol/disco#items"
        query.addElement("feature").attributes["var"] = "http://jabber.org/protocol/disco#info"

        self.h2x.send(iq)
Example #43
0
    def componentIq(self, element: Element, sender: JID, identifier: str, iqType: str):
        for query in element.elements():
            xmlns = query.uri
            node = query.getAttribute("node")

            if xmlns == "http://jabber.org/protocol/disco#info" and iqType == "get":
                self.__getDiscoInfo(sender, identifier, node)
                return

            if xmlns == "http://jabber.org/protocol/disco#items" and iqType == "get":
                self.__getDiscoItems(sender, identifier, node)
                return

            if xmlns == "jabber:iq:register" and iqType == "get":
                self.__getRegister(sender, identifier)
                return

            if xmlns == "jabber:iq:register" and iqType == "set":
                self.__setRegister(element, sender, identifier)
                return

            if xmlns == "http://jabber.org/protocol/commands" and query.name == "command" and iqType == "set":
                self.__command(query, sender, identifier, node)
                return

            self.__sendIqError(
                recipient=sender.full(),
                sender=self.h2x.config.JID,
                identification=identifier,
                errorType="cancel",
                condition="feature-not-implemented",
            )
Example #44
0
 def JID2Hang(self, jid: JID):
     if not self.h2x.isHangUser(jid):
         raise Exception(jid.full() + " is not valid user JID for the transport")
     userIdParts = jid.user.split(".")
     userChatId = userIdParts[0]
     userGaiaId = userIdParts[1]
     return hangups.user.UserID(userChatId, userGaiaId)
Example #45
0
def idiotic(msg):
        """Suck some cocks."""

        # return str(request.body)
        message_from = JID(msg['from'])
        message_bare_from = message_from.userhost()
        message_user = (yield objs.User.find_one({'jids': message_bare_from}))
        if not message_user:
            message_user = (yield objs.User.find_one({'jid': message_bare_from}))

        # if message.body is None:
        #    return ''

        if msg.bnw_s2s:
            bnw_s2s = msg.bnw_s2s
            print 'GOT AN s2s MESSAGE', bnw_s2s
            try:
                s2s_type = bnw_s2s['type']
            except KeyError:
                s2s_type = None
            handler = handlers.s2s_handlers.get(s2s_type)
            if not handler:
                print 'NO HANDLER FOR THIS TYPE (%s)' % (s2s_type)
            else:
                _ = yield handler(msg, bnw_s2s)
            defer.returnValue(None)
        message_body = unicode(msg.body)

        if message_body is None:
            defer.returnValue('')
        message_body = message_body.strip()
        if type(message_body) != unicode:
            message_body = unicode(message_body, 'utf-8', 'replace')
        xmsg = XmppMessage(
            message_body, JID(msg['to']), message_from, message_user)

        if message_user:
            message_user.activity()
        try:
            iparser = 'redeye'
            if message_user:
                if 'interface' in message_user:
                    iparser = message_user['interface']
            result = yield handlers.parsers[iparser].handle(xmsg)
        except CommandParserException, exc:
            result = yield exc.args[0]
Example #46
0
    def onIq(self, element: Element):
        source = JID(element.getAttribute("from"))
        recipient = JID(element.getAttribute("to"))
        identification = element.getAttribute("id")
        iqType = element.getAttribute("type")

        print("IqReceived " + source.full() + " -> " + recipient.full() + ": " + iqType)

        # Process component iq
        if recipient.full() == self.h2x.config.JID:
            self.componentIq(element, source, identification, iqType)
            return

            # Process user iq
        if self.h2x.isHangUser(recipient):
            self.userIq(element, source, recipient, identification, iqType)
            return

            # TODO: Can we send something like wrong request?
        self.__sendIqError(
            recipient=source.full(),
            sender=recipient.full(),
            identification=identification,
            errorType="cancel",
            condition="service-unavailable",
        )
Example #47
0
def unavailable(prot, presence):
    global chatrooms

    fromjid = JID(presence["from"])
    tojid = JID(presence["to"])

    log.msg("Unavailable from:  %s to %s (my jid is %s)" % (fromjid, tojid, prot.jid))

    room_name = tojid.user

    log.msg("Room name:  %s, user nick:  %s, host: %s" % (room_name, tojid.resource, tojid.host))

    assert tojid.host == prot.jid

    prot.presenceBroadcast(room_name, tojid.resource, "unavailable")

    room = chatrooms[room_name]
    del room[fromjid.full()]
Example #48
0
    def __setRegister(self, data: Element, sender: JID, identifier: str):
        try:
            user = sender.userhost()
            token = data.firstChildElement().firstChildElement().firstChildElement().firstChildElement().__str__()
        except Exception as e:
            # Fail registration
            print("Register reponse processing failed: " + e.__str__())
            # FIXME: Send negative response here !!!
            self.__sendIqResult(sender.full(), self.h2x.config.JID, identifier, "jabber:iq:register")
            return

        self.h2x.registerUser(user, token)

        # Send registration done
        self.__sendIqResult(sender.full(), self.h2x.config.JID, identifier, "jabber:iq:register")

        # Request subscription
        self.h2x.sendPresence(sender, "subscribe")
Example #49
0
def iq(msg):
    """Process incoming IQ stanza."""
    try:
        iq_from = JID(msg['from'])
        iq_bare_from = iq_from.userhost()
        iq_user = (yield objs.User.find_one({'jids': iq_bare_from}))
        if not iq_user:
            iq_user = (yield objs.User.find_one({'jid': iq_bare_from}))

        for handler in iq_handlers.handlers:
            if (yield handler(msg, iq_user)):
                defer.returnValue(True)
        defer.returnValue(False)
    except Exception:
        raise
        print ("Error while processing iq:\n\n" +
               traceback.format_exc() + "\n" +
               "Command which caused this exception: " + iq)
Example #50
0
 def call_msg_handlers(self, t, s, b, subject, stanza):
  if t == 'error': return
  if subject:
   j = JID(s)
   if not j.userhost() in self.g.keys():
    self.log.log('ignored subject from %s, stanza was %s' % (escape(s), escape(stanza.toXml())), 3)
   else:
    self.log.log('got subject from %s, stanza was %s, let\'s call topichandlers' % (escape(s), escape(stanza.toXml())), 1)
    if j.resource:
     for i in self.topichandlers: self.call(i, s, subject)
    else:
     for i in self.topichandlers: self.call(i, s, b)
  else:
   delayed = [i for i in stanza.children if (i.__class__==domish.Element) and ((i.name=='delay') or ((i.name=='x') and (i.uri=='jabber:x:delay')))]
   if delayed: dl = True
   else: dl = False
   for i in self.msghandlers:
    if (t == 'groupchat') or not i[1]: self.call(i[0], s, b, dl)
Example #51
0
	def sendPresence(self, destination: JID, presenceType: str, status: str = None, show: str = None,
					 priority: int = None, source: JID = None, nick: str = None):
		if not source:
			source = JID(self.config.JID)
		presence = Element((None, 'presence'))
		presence.attributes['to'] = destination.userhost()
		presence.attributes['from'] = source.userhost()
		presence.attributes['type'] = presenceType
		if status:
			presence.addElement('status').addContent(status)
		if show:
			presence.addElement('show').addContent(show)
		if priority:
			presence.addElement('priority').addContent(priority)
		if nick:
			nickElement = presence.addElement('nick', content=nick)
			nickElement.attributes["xmlns"] = "http://jabber.org/protocol/nick"
		print("PresenceSend: " + source.full() + " -> " + destination.full() + " : " + presenceType)
		self.send(presence)
Example #52
0
 def call_msg_handlers(self, t, s, b, subject, stanza):
     if t == "error":
         return
     if subject:
         j = JID(s)
         if not j.userhost() in self.g.keys():
             self.log.log("ignored subject from %s, stanza was %s" % (escape(s), escape(stanza.toXml())), 3)
         else:
             self.log.log(
                 "got subject from %s, stanza was %s, let's call topichandlers"
                 % (escape(s), escape(stanza.toXml())),
                 1,
             )
             for i in self.topichandlers:
                 self.call(i, s, subject)
     else:
         for i in self.msghandlers:
             if (t == "groupchat") or not i[1]:
                 self.call(i[0], s, b)
Example #53
0
    def __getVCard(self, sender: JID, recipient: JID, identifier):
        iq = Element((None, "iq"))
        iq.attributes["type"] = "result"
        iq.attributes["from"] = recipient.full()
        iq.attributes["to"] = sender.full()
        if identifier:
            iq.attributes["id"] = identifier
        vcard = iq.addElement("vCard")
        vcard.attributes["xmlns"] = "vcard-temp"

        userInfo = self.h2x.getClient(sender).getUser(recipient)

        # TODO: Get more user info
        vcard.addElement("FN", content=userInfo.full_name)
        vcard.addElement("NICKNAME", content=userInfo.full_name)
        emails = vcard.addElement("EMAIL")
        for email in userInfo.emails:
            emails.addElement("USERID", content=email)

        self.h2x.send(iq)
Example #54
0
	def onPresence(self, element: Element):
		sender = JID(element.getAttribute("from"))
		recipient = JID(element.getAttribute("to"))
		presenceType = element.getAttribute("type")
		if not presenceType:
			presenceType = "available"

		print("PresenceReceived: " + sender.full() + " -> " + recipient.full() + " : " + presenceType)

		# Create client instance on available from XMPP client
		if self.getClient(sender) is None:
			if presenceType == "available":
				try:
					self.addClient(ClientWrapper(self, sender))
				except UserNotRegistered as e:
					print(e)
					self.sendPresenceError(recipient=sender, sender=recipient, errorType="auth",
										   condition="registration-required")
					return
			else:
				print("Operation on client which has not yet send available presence !!! (responding as if we are not available)")
				self.sendPresence(sender, "unavailable")
				return

		# Service component presence
		if recipient == JID(self.config.JID):
			self.getClient(sender).processComponentPresence(sender, presenceType, recipient)

		# Subscription request
		elif presenceType == "subscribe":
			self.getClient(sender).processSubscription(recipient)

		# Presence to Hangouts user
		elif self.isHangUser(recipient):
			self.getClient(sender).processPresence(recipient, presenceType)

		# Unimplemented feature
		else:
			raise NotImplemented(element)
Example #55
0
 def install(self, _parentService):
     """interface requirement"""
     self.parentService = _parentService
     user = self.SERVICECONFIG.JABBER_USERNAME
     server = self.SERVICECONFIG.JABBER_SERVER
     resource = self.SERVICECONFIG.JABBER_RESOURCE
     self.jid = JID("%(user)s@%(server)s/%(resource)s" % locals())
     self.broadcastTask = LoopingCall(self.broadcastPresence)
     self.sendQueue = []
     self.authenticated = False
     #load all jabber responders, after configuration
     import droned.responders
     droned.responders.loadAll()
Example #56
0
def present(prot, presence):
    global chatrooms

    fromjid = JID(presence["from"])
    tojid = JID(presence["to"])

    log.msg("Available from:  %s to %s (my jid is %s)" % (fromjid, tojid, prot.jid))

    room_name = tojid.user

    log.msg("Room name:  %s, user nick:  %s, host: %s" % (room_name, tojid.resource, tojid.host))

    assert tojid.host == prot.jid
    if room_name not in chatrooms:
        chatrooms[room_name] = ChatRoom(room_name)
    chatrooms[room_name].add(ChatUser(tojid.resource, fromjid.full()))

    prot.presenceBroadcast(room_name, tojid.resource)

    # Send The current list to the new user
    for u in chatrooms[room_name].users:
        prot.sendOnePresence(room_name, u.nick, "participant", fromjid, None)
Example #57
0
        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
Example #58
0
    def __getRegister(self, sender: JID, identifier: str):
        iq = Element((None, "iq"))
        iq.attributes["type"] = "result"
        iq.attributes["from"] = self.h2x.config.JID
        iq.attributes["to"] = sender.full()
        if identifier:
            iq.attributes["id"] = identifier
        query = iq.addElement("query")
        query.attributes["xmlns"] = "jabber:iq:register"

        # Create registration form
        form = Form(query)
        form.addTitle("Hangouts registration form")
        form.addTextBox("token", "Replace link by token", hangups.auth.OAUTH2_LOGIN_URL, required=True)
        self.h2x.send(iq)