Пример #1
0
    def vipadia_iq(self, iq):
        dbg("vipadia_iq:\n%s" % (fmt_evt(iq),), 3)

        items = iq.xpath_eval("v:query/v:item", { "v": "http://vipadia.com/skype", })
        for item in items:
            jid = JID(item.prop("dialback"))
            (_, screen, _) = jid.resource.split(":")
            secret = item.prop("secret")
            skypeuser = item.prop("skypeuser")
            skypesecret = item.prop("skypesecret")
            xmppujid = item.prop("xmppujid")
            mode = item.prop("mode")
            marketing_message = item.prop("marketing-message")

            argstring = base64.b64encode(
                "%s\0%s\0%s\0%s\0%s\0%s\0%s\0%s\0%s\0%s" % (
                jid.as_utf8(), secret,
                skypeuser, skypesecret, xmppujid,
                mode, self.config.master, self.config.muc,
                "%s@%s" % (self.config.slave, self.config.domain),
                marketing_message,
                ))
            cmd = [ "./karaka/bundle.sh", screen, argstring ] 
            dbg("  cmd:%s"  % (cmd,))
            ps = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        
        return True
Пример #2
0
	def session_started(self):
		"""This is called when the IM session is successfully started
		(after all the neccessery negotiations, authentication and
		authorizasion).
		That is the best place to setup various handlers for the stream.
		Do not forget about calling the session_started() method of the base
		class!"""
		JabberClient.session_started(self)

		# set up handlers for supported <iq/> queries
		self.stream.set_iq_get_handler("query","jabber:iq:version",self.get_version)

		# set up handlers for <presence/> stanzas
		self.stream.set_presence_handler("available",self.presence)
		self.stream.set_presence_handler("subscribe",self.presence_control)
		self.stream.set_presence_handler("subscribed",self.presence_control)
		self.stream.set_presence_handler("unsubscribe",self.presence_control)
		self.stream.set_presence_handler("unsubscribed",self.presence_control)

		# set up handler for <message stanza>
		self.stream.set_message_handler("normal",self.message)
		print(self.stream)

		print u"joining..."
		self.roommgr = MucRoomManager(self.stream)
		self.roommgr.set_handlers()
		nick = self.jid.node + '-' + self.jid.resource
		for loc in options.channels: #['*****@*****.**','*****@*****.**']:
			roomjid = JID(loc, options.muc)
			print("\t %s" % roomjid.as_unicode())
			h = RoomHandler()
			self.muc.append(h)
			mucstate = self.roommgr.join(roomjid, nick, h)
			h.assign_state(mucstate)
Пример #3
0
 def slave_online(self):
     slavejid = JID("%s@%s/slave" % (self.config.slave, self.config.domain))
     iq = Iq(to_jid=self.config.master, from_jid=slavejid, stanza_type="set")
     command = iq.new_query('http://vipadia.com/skype', "command")
     digest = generate_slave_digest(str(slavejid.as_utf8()),
                                    self.config.slave_secret)
     add_child(command, "item", attrs={ "command": "slave-online",
                                        "capacity": self.config.capacity,
                                        "base": self.config.base,
                                        "digest": digest
                                        })
     dbg("  iq:\n%s" % (fmt_evt(iq),))
     self.safe_send(iq)
Пример #4
0
    def vipadia_command(self, iq):
        dbg("vipadia_command:\n%s" % (fmt_evt(iq),))

        items = iq.xpath_eval("v:command/v:item", { "v": "http://vipadia.com/skype", })
        for item in items:
            command = item.prop("command")
            if command == "message":
                ujid = JID(item.prop("ujid"))
                message = item.prop("message")

                dbg("  +ujid:%s precedingmessage:%s" % (ujid.as_utf8(), PrecedingMessage,))
                if ujid in PrecedingMessage and PrecedingMessage[ujid] == message:
                    continue

                PrecedingMessage[ujid] = message
                self.safe_send(Message(to_jid=ujid, body=message))
                dbg("  -ujid:%s precedingmessage:%s" % (ujid.as_utf8(), PrecedingMessage,))

        return True
Пример #5
0
    def _spawn(self, frm, user, secret):
        dbg("_spawn: frm:%s user:%s secret:%s" % (frm.as_utf8(), user, secret))

        ujid = frm.bare()
        
        ## don't spawn if one already exists for this user
        if ujid in St['users']: return
        
        self.regdb.log_start(ujid.as_utf8(), user) # log it

        (slavejid, screen) = self.allocate_djid()
        if not slavejid: return "resource-constraint"

        djid = JID("%s@%s/%s:%s:%s" % (
            self.config.dialback, self.config.domain, slavejid.node, screen, hash(ujid)))

        dbg("  before avail: St['slots']:%s  St['dialback_slave']:%s" % (
            St['slots'], St['dialback_slave']))
        St['slots'][slavejid][screen] = djid
        St['dialback_slave'][djid] = (slavejid, screen)
        dbg("  after avail: St['slots']:%s  St['dialback_slave']:%s" % (
            St['slots'], St['dialback_slave']))

        St['dialbacks'][djid] = ujid
        St['users'][ujid] = djid
        if ujid not in St['userjids']: St['userjids'][ujid] = {}
        St['userjids'][ujid][frm] = None

        St['dialback_online'][djid] = DIALBACK.pending

        spawn = Iq(to_jid=slavejid, from_jid=self.config.component, stanza_type="set")
        query = spawn.new_query('http://vipadia.com/skype', "query")
        add_child(query, "item",
                  attrs={ "skypeuser": user,
                          "skypesecret": secret,
                          "dialback": djid.as_utf8(),
                          "secret": self.config.dialback_secret,
                          "xmppujid": ujid.as_utf8(),
                          "mode": CLIENT_MODE,
                          "marketing-message": self.regdb.get_marketing_message(frm.as_utf8()),
                          })
        dbg("  spawn:\n%s" % (fmt_evt(spawn),))
        self.safe_send(spawn)
Пример #6
0
    def __init__(self, config):
        self.config = config
        self.connection = CONNECTION.idle
        self.running = True
        
        self.jid = JID("%s@%s/%s" % (config.register, config.domain, config.register))
        log("register: jid:%s" % (self.jid.as_utf8(),))
        
        tls = streamtls.TLSSettings(require=True, verify_peer=False)
        auth = [ 'digest' ]

        JabberClient.__init__(self, self.jid, self.config.secret,
            disco_name="Vipadia Skype Gateway Register", disco_type="bot",
            tls_settings=tls, auth_methods=auth)
Пример #7
0
    def announce(self, message):
        """ send message to all owners"""
        for user in self.getConfig("owners").split(";"):
            self.logDebug("pyLoad XMPP: Send message to %s" % user)

            to_jid = JID(user)

            m = Message(from_jid=self.jid,
                        to_jid=to_jid,
                        stanza_type="chat",
                        body=message)

            stream = self.get_stream()
            if not stream:
                self.connect()
                stream = self.get_stream()

            stream.send(m)
Пример #8
0
    def connect(self, tls_cacerts=None):
        self.set_encoding()
        self.set_logging()

        print u"creating client..."
        # JID password ['tls_noverify'|cacert_file]
        self._client = Client(JID(self._username),
                              password=self._password,
                              server=self._server,
                              port=self._port,
                              channel=self._channel,
                              tls_cacerts=tls_cacerts,
                              listener=self._listener)

        print u"connecting..."
        self._client.connect()
        self.start()

        return True
Пример #9
0
    def __init__(self, jid, password):

        # if bare JID is provided add a resource -- it is required
        if not jid.resource:
            print(jid.resource)
            jid = JID(jid.node, jid.domain, "Echobot")

        # setup client with provided connection information
        # and identity data
        JabberClient.__init__(self,
                              jid,
                              password,
                              disco_name="PyXMPP example: echo bot",
                              disco_type="bot",
                              keepalive=10)

        # register features to be announced via Service Discovery
        self.disco_info.add_feature("jabber:iq:version")
        self.muc = []
Пример #10
0
 def __init__(self, cache, jid, node=None, name=None):
     self.lock = RLock()
     self.cache = cache
     #jid of this item
     self.jid = JID(jid)
     #node part of address
     self.node = node
     #Item description
     self.name = name
     #a list of namespaces
     self.features = []
     #a list of DiscoIdentStorage with category(req), type(req), and name(opt)
     self.identities = []
     #a list of "child" DiscoNode
     self.items = []
     self.info_error_data = False
     self.items_error_data = False
     self._info_outstanding = False
     self._items_outstanding = False
     self._children_outstanding = 0
Пример #11
0
    def invite(self, buddy, message=None, callback=None):
        '''
        Sends an invite for this room to "buddy" (its actually a <message /> to
        the room--the room sends an invite "on your behalf").

        <message
            from='[email protected]/desktop'
            to='*****@*****.**'>
          <x xmlns='http://jabber.org/protocol/muc#user'>
            <invite to='*****@*****.**'>
              <reason>
                Hey Hecate, this is the place for all good witches!
              </reason>
            </invite>
          </x>
        </message>
        '''
        room = self

        try:
            buddy = buddy.jid.as_unicode()
        except:
            buddy = JID(buddy).as_unicode()

        if message is None:
            message = _('You have been invited to {roomname}').format(
                roomname=self.jid.as_unicode())

        # Send an invitation "by way" of room
        m = Message(from_jid=room.protocol.self_buddy.jid, to_jid=room.jid)

        # <x tag>
        x = m.xmlnode.newTextChild(None, 'x', None)
        x.setNs(x.newNs('http://jabber.org/protocol/muc#user', None))

        # <invite to="buddy to invite"><reason>Plz come chat</reason></invite>
        invite = x.newTextChild(None, 'invite', None)
        invite.setProp('to', buddy)
        reason = invite.newTextChild(None, 'reason', message)

        self.protocol.send_cb(m, callback=callback)
Пример #12
0
 def __init__(self, config, logger):
     """Create instance and initialize from configuration options.
     Also set logger to global default one."""
     self.serverOpts = config.getOptions('server')
     self.mysqlOpts = config.getOptions('mysql')
     self.compOpts = config.getOptions('component')
     # initialize component
     logger.info('JoggerBot component initializing')
     name = self.compOpts['name']
     secret = self.serverOpts['secret']
     serverHostname = self.serverOpts['hostname']
     port = int(self.serverOpts['port'])
     try:
         fullName = self.compOpts['fullname']
     except KeyError:
         # using old configuration data
         self.logger.warning('Old configuration data is used')
         fullName = name
     Component.__init__(self,
                        JID(name),
                        secret,
                        serverHostname,
                        port,
                        disco_name=fullName,
                        disco_category='x-service',
                        disco_type='x-jogger')
     self.disco_info.add_feature('jabber:iq:version')
     logger.info('JoggerBot component initialized')
     self.startTime = time.time()
     self.cfg = config
     self.logger = logger
     # the signals we should respond to with graceful exit
     # for debug purpose also check Win platform
     if sys.platform == 'win32':
         signals = (signal.SIGTERM, signal.SIGINT)
     else:
         signals = (signal.SIGHUP, signal.SIGKILL, signal.SIGTERM,
                    signal.SIGINT)
     for sign in signals:
         signal.signal(sign, self.shutdown)
     self._connectDB()
Пример #13
0
 def session_started(self):
     """Triggered when the session starts. Sets some event handlers and
     connects to indicated rooms
     
     """
     JabberClient.session_started(self)
     self.stream.set_message_handler("chat", self.chat_received)
     self.stream.set_message_handler("error", self.error_received)
     self.stream.set_presence_handler(None, self.presence_received)
     self.stream.set_presence_handler("unavailable",
                                      self.unavailable_received)
     self.stream.set_presence_handler("subscribe",
                                      self.subscription_received)
     self.stream.set_presence_handler("unsubscribe",
                                      self.subscription_received)
     self.stream.set_presence_handler("subscribed",
                                      self.subscription_received)
     self.stream.set_presence_handler("unsubscribed",
                                      self.subscription_received)
     self.logger.info("Session started")
     self.mucman = MucRoomManager(self.stream)
     self.mucman.set_handlers()
     for room in self.rooms_to_join:
         self.join_room(JID(room))
Пример #14
0
    def __init__(self, jid, password, tls_cacerts):
        # if bare JID is provided add a resource -- it is required
        if not jid.resource:
            jid=JID(jid.node, jid.domain, "attacktest")

        if tls_cacerts:
            if tls_cacerts == 'tls_noverify':
                tls_settings = TLSSettings(require = True, verify_peer = False)
            else:
                tls_settings = TLSSettings(require = True, cacert_file = tls_cacerts)
        else:
            tls_settings = None

        # setup client with provided connection information
        # and identity data
        JabberClient.__init__(self, jid, password,
                disco_name="PyXMPP example: echo bot", disco_type="bot",
                tls_settings = tls_settings)

        # add the separate components
        self.interface_providers = [
            VersionHandler(self),
            EchoHandler(self),
            ]
Пример #15
0
 def sendUnsubscribe(self, to):
     toJID = JID(to)
     p = Presence(to_jid=toJID,
                  from_jid=self.jid,
                  stanza_type='unsubscribe')
     self.stream.send(p)
Пример #16
0
 def create_jid(self, jid):
     """Creates an apropiate jid"""
     jid_ = JID(jid)
     if not jid_.resource:
         return JID(jid_.node, jid_.domain, self.__class__.__name__)
     return jid_
Пример #17
0
def get_from(stanza):
    frm = stanza.get_from()
    resource = frm.resource
    if not resource: resource = ""
    return JID("%s@%s/%s" % (frm.node.lower(), frm.domain.lower(), resource))
Пример #18
0
 def session_started(self):
     self._session_started_helper(MucClient(), JID(ROOM, SERVER))
Пример #19
0
re_plugin = re.compile('[^.].*\.py$')
for plugin_file in os.listdir(plugin_directory):
    if re_plugin.match(plugin_file):
        name = plugin_file[:-3]
        print 'Loading %s' % name
        plugin_info = imp.find_module(name, [plugin_directory])
        plugin = imp.load_module(name, *plugin_info)
        plugins[name] = plugin

        # Load the verbs supported by this plugin
        for verb in plugin.Verbs():
            verbs[verb] = name

print u'Creating client...'
password_verifier = PasswordCache(password_filename)
if not require_auth:
    password_verifier = NoAuthentication()
c = BotClient(JID(account), password, password_verifier, outbox_directory)

print u'Connecting...'
c.connect()

print u'Connected'
try:
    # The client class provides a basic "main loop" for the application.
    c.loop(1)

except KeyboardInterrupt:
    print u'Disconnecting'
    c.disconnect()
Пример #20
0
    print 'Preparing Facebook client...'
    global_fb_client = get_fb_client()

    try:
        my_uid = str(global_fb_client.uid)
        to_uid = sys.argv[1]
        message = unicode(sys.argv[2])
        my_jid = '-' + my_uid + '@chat.facebook.com/TestClient'
    except IndexError:
        sys.exit('usage: %s {to_uid} {message}' % sys.argv[0])

    print 'Creating stream...'
    xmpp_client = FacebookChatClient(
        to_uid=to_uid,
        message=message,
        jid=JID(my_jid),
        password=u'ignored',
        auth_methods=['sasl:X-FACEBOOK-PLATFORM'],
        #server = 'localhost'
    )

    print 'Connecting...'
    xmpp_client.connect()

    print 'Processing...'
    try:
        xmpp_client.loop(1)
    finally:
        xmpp_client.disconnect()
Пример #21
0
    def message(self, stanza):
        dbg("message:\nfrm:%s to:%s" % (
            stanza.get_from().as_utf8(), stanza.get_to().as_utf8(),), 3)
        global RegDB
        
        body = stanza.get_body()
        frm = stanza.get_from()
        user = stanza.get_from().bare().as_utf8()

        ujid = JID(user)
        dbg("  ++ujid:%s precedingmessage:%s" % (ujid.as_utf8(), PrecedingMessage,))
        if ujid in PrecedingMessage: del PrecedingMessage[ujid]
        dbg("  --ujid:%s precedingmessage:%s" % (ujid.as_utf8(), PrecedingMessage,))
                                                               
        if body:         
            cmd = body.split()
            if len(cmd) > 0 :
                reply = ""
                if cmd[0].lower() == "register":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"

                    skypeuser = cmd[1]
                    skypepass = cmd[2]
                    
                    RegDB.remove_credentials(user)
                    RegDB.set_credentials_plain(user, skypeuser, skypepass)
                                                                     
                    reply = "Registration successful for " + skypeuser
                    message = Message(to_jid=stanza.get_from(), body=reply)
                    self.safe_send(message)

                    sub = Iq(to_jid=self.config.master, stanza_type="set")
                    query = sub.new_query('http://vipadia.com/skype', "command")
                    add_child(query, "item", attrs={ "command" : "register-available",
                                                     "jid": frm.as_utf8() })
                    dbg("  sub:\n%s" % (fmt_evt(sub),))
                    self.safe_send(sub)
                    reply = "Presence request sent"

                elif cmd[0].lower() == "register-carrier":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"
                        
                    skypeuser = cmd[1]
                    ## KeyCzar
##                     crypter = keyczar.Encrypter.Read(PUBLIC_KEYLOC)
                    skypesecret = cmd[2]
                    ## KeyCzar
##                     skypesecret = crypter.Encrypt(str(skypesecret))
                    
                    spawn = Iq(to_jid=self.config.master, stanza_type="set")
                    command = spawn.new_query("http://vipadia.com/skype", "command")
                    add_child(command, "item", attrs={ "command": "spawn",
                                                       "ujid": frm.as_utf8(),
                                                       "skypeuser": skypeuser,
                                                       "skypesecret": skypesecret,
                                                       })
                    self.safe_send(spawn)
                    
                elif cmd[0].lower() == "unregister":
                    if len(cmd) == 1:
                        RegDB.remove_credentials(user)
                        reply = "Unregistration successful"

                else:
                    reply = "Skype Registration Commands:\r\n" + \
                    " register <skypeuser> <skypepass>\r\n" + \
                    " unregister"
                
                message = Message(to_jid=stanza.get_from(), body=reply)
                self.safe_send(message)
        
        return True
Пример #22
0
# PyXMPP uses `logging` module for its debug output
# applications should set it up as needed
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

if len(sys.argv) < 5:
    print "Usage:"
    print "\t%s name secret server port" % (sys.argv[0], )
    print "example:"
    print "\t%s echo.localhost verysecret localhost 5347" % (sys.argv[0], )
    sys.exit(1)

print "creating component..."
c = Component(JID(sys.argv[1]), sys.argv[2], sys.argv[3], int(sys.argv[4]))

print "connecting..."
c.connect()

print "looping..."
try:
    # Component class provides basic "main loop" for the applitation
    # Though, most applications would need to have their own loop and call
    # component.stream.loop_iter() from it whenever an event on
    # component.stream.fileno() occurs.
    c.loop(1)
except KeyboardInterrupt:
    print "disconnecting..."
    c.disconnect()
    pass
Пример #23
0
 def _create_jabber_user(self, nick, channel):
     jid = JID(nick, domain=self.settings.JABBER_JID, resource=nick)
     sender = self.jjc.join_room(channel, jid)
     self.jabber_users[nick] = ObjDict(jid=jid,
                                       sender=sender,
                                       room_jid=channel)
Пример #24
0
    def handle_message(self, msg):
        logging.info(msg)
        if msg.what == 'IRC_CONNECT':
            self.irc_connected = True
            if self.jabber_connected:
                self._fully_connected()

        elif msg.what == 'JABBER_CONNECT':
            self.jabber_connected = True
            if self.irc_connected:
                self._fully_connected()

        elif msg.what == 'IRC_CHANNEL_MESSAGE':
            jid = self.jabber_channels.get(msg.subject, None)
            if jid is not None:
                jabber_user = self.jabber_users.get(msg.sender, None)
                if jabber_user:
                    self.jjc.send_to_room(jabber_user.room_jid,
                                          jabber_user.jid, msg.body)

        elif msg.what == 'JABBER_CHANNEL_MESSAGE':
            chan = self.irc_channels.get(msg.subject, None)
            if chan is not None:
                irc_user = self.irc_users.get(msg.sender, None)
                if irc_user:
                    self.jic.send_to_channel(irc_user.irc_nick,
                                             irc_user.irc_channel, msg.body)

        elif msg.what == 'JABBER_CHANNEL_JOIN':
            irc_nick = self.jic.unique_nick(msg.nick)

            jid = getattr(
                msg, 'jid',
                '%s@%s/%s' % (msg.nick, self.settings.JABBER_JID, irc_nick))
            jid = self._jid_re.match(jid).groupdict()
            channel = self._jid_re.match(msg.channel).groupdict()['node']

            if JID(msg.sender) not in [
                    j.sender for j in self.jabber_users.values()
            ] and msg.sender not in self.irc_users:
                # dont create IRC users for our own jabber users presence stanzas or for users weve already created
                self.irc_users[msg.sender] = ObjDict(
                    jid=jid,
                    irc_nick=irc_nick,
                    irc_channel=channel,
                    xmpp_nick=msg.nick,
                    role=msg.role,
                    affiliation=msg.affiliation)
                self.jic.introduce_nick(irc_nick,
                                        username=jid['node'],
                                        hostname=jid['domain'],
                                        info=jid['resource'])
                self.jic.join_channel(irc_nick, channel)

        elif msg.what == 'JABBER_NICK_CONFLICT':
            msg.sender
            for nick, jabber_user in self.jabber_users.items():
                if msg.sender == jabber_user.sender.as_utf8():
                    nick = jabber_user.sender.resource + '_'
                    jabber_user.sender = self.jjc.join_room(
                        jabber_user.room_jid, jabber_user.jid, nick=nick)
                    break

        elif msg.what == 'JABBER_CHANNEL_PART':
            irc_user = self.irc_users.get(msg.sender, None)
            if irc_user:
                self.jic.part_channel(irc_user.irc_nick, irc_user.irc_channel)
                self.jic.quit_nick(irc_user.irc_nick)
                del self.irc_users[msg.sender]

        elif msg.what == 'IRC_CHANNEL_JOIN':
            self._create_jabber_user(msg.sender,
                                     self.jabber_channels[msg.channel])

        elif msg.what == 'IRC_CHANNEL_PART':
            jabber_user = self.jabber_users.get(msg.sender, None)
            if jabber_user:
                self.jjc.part_room(jabber_user.room_jid, jabber_user.jid)
                del self.jabber_users[msg.sender]
Пример #25
0
    def message(self, stanza):
        body = stanza.get_body()
        frm = stanza.get_from().as_utf8().split('@')[0]
        if stanza.get_type() == "headline": return True
        print colorize('g', frm + ':'), body
        response = self.autorespond(body)
        return Message(to_jid=stanza.get_from(),
                       from_jid=stanza.get_to(),
                       stanza_type=stanza.get_type(),
                       subject=stanza.get_subject(),
                       body=response)


#end class

if len(sys.argv) != 2:
    print notify('!', 'r', "Usage: %s <nick_to_clone>" % sys.argv[0])
    sys.exit(1)
nick = sys.argv[1]

if ROOM_TYPE == 'MUC':
    jidname = nick + '@' + DOMAIN
else:
    sys.exit(notify('!', 'r', "%s is not supported yet" % ROOM_TYPE))
jidname = getuser() + '@' + DOMAIN

mucroombot.setup_localization()
while mucroombot.main(lambda: CloneClient(JID(jidname), getpass(), nick)):
    pass
    # vi: sts=4 et sw=4
Пример #26
0
class _Register(JabberClient):
    def __init__(self, config):
        self.config = config
        self.connection = CONNECTION.idle
        self.running = True

        self.jid = JID("%s@%s/%s" %
                       (config.register, config.domain, config.register))
        log("register: jid:%s" % (self.jid.as_utf8(), ))

        tls = streamtls.TLSSettings(require=True, verify_peer=False)
        auth = ['digest']

        JabberClient.__init__(self,
                              self.jid,
                              self.config.secret,
                              disco_name="Vipadia Skype Gateway Register",
                              disco_type="bot",
                              tls_settings=tls,
                              auth_methods=auth)

    def stream_state_changed(self, state, arg):
        dbg("stream_state_changed: %s %r" % (state, arg), 3)

    def safe_send(self, stanza):
        to = stanza.get_to()
        if not to.domain.endswith(self.config.domain): to = to.bare()

        stanza = Stanza(stanza, to_jid=to)
        dbg("tx:\n%s" % (fmt_evt(stanza), ))
        self.stream.send(stanza)

    def session_started(self):
        log("session_started: jid:%s" % (self.jid.as_utf8(), ))

        self.connection = CONNECTION.connected
        JabberClient.session_started(self)

        self.stream.set_message_handler("normal", self.message)
        self.stream.set_presence_handler("subscribe", self.subscription)
        self.stream.set_iq_set_handler("command", "http://vipadia.com/skype",
                                       self.vipadia_command)

        global Connected
        Connected = True

        self.safe_send(
            Presence(to_jid=self.config.master, stanza_type="subscribe"))

    #
    # message handler
    #

    def message(self, stanza):
        dbg(
            "message:\nfrm:%s to:%s" % (
                stanza.get_from().as_utf8(),
                stanza.get_to().as_utf8(),
            ), 3)
        global RegDB

        body = stanza.get_body()
        frm = stanza.get_from()
        user = stanza.get_from().bare().as_utf8()

        ujid = JID(user)
        dbg("  ++ujid:%s precedingmessage:%s" % (
            ujid.as_utf8(),
            PrecedingMessage,
        ))
        if ujid in PrecedingMessage: del PrecedingMessage[ujid]
        dbg("  --ujid:%s precedingmessage:%s" % (
            ujid.as_utf8(),
            PrecedingMessage,
        ))

        if body:
            cmd = body.split()
            if len(cmd) > 0:
                reply = ""
                if cmd[0].lower() == "register":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"

                    skypeuser = cmd[1]
                    skypepass = cmd[2]

                    RegDB.remove_credentials(user)
                    RegDB.set_credentials_plain(user, skypeuser, skypepass)

                    reply = "Registration successful for " + skypeuser
                    message = Message(to_jid=stanza.get_from(), body=reply)
                    self.safe_send(message)

                    sub = Iq(to_jid=self.config.master, stanza_type="set")
                    query = sub.new_query('http://vipadia.com/skype',
                                          "command")
                    add_child(query,
                              "item",
                              attrs={
                                  "command": "register-available",
                                  "jid": frm.as_utf8()
                              })
                    dbg("  sub:\n%s" % (fmt_evt(sub), ))
                    self.safe_send(sub)
                    reply = "Presence request sent"

                elif cmd[0].lower() == "register-carrier":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"

                    skypeuser = cmd[1]
                    ## KeyCzar
                    ##                     crypter = keyczar.Encrypter.Read(PUBLIC_KEYLOC)
                    skypesecret = cmd[2]
                    ## KeyCzar
                    ##                     skypesecret = crypter.Encrypt(str(skypesecret))

                    spawn = Iq(to_jid=self.config.master, stanza_type="set")
                    command = spawn.new_query("http://vipadia.com/skype",
                                              "command")
                    add_child(command,
                              "item",
                              attrs={
                                  "command": "spawn",
                                  "ujid": frm.as_utf8(),
                                  "skypeuser": skypeuser,
                                  "skypesecret": skypesecret,
                              })
                    self.safe_send(spawn)

                elif cmd[0].lower() == "unregister":
                    if len(cmd) == 1:
                        RegDB.remove_credentials(user)
                        reply = "Unregistration successful"

                else:
                    reply = "Skype Registration Commands:\r\n" + \
                    " register <skypeuser> <skypepass>\r\n" + \
                    " unregister"

                message = Message(to_jid=stanza.get_from(), body=reply)
                self.safe_send(message)

        return True

    #
    # presence handlers
    #

    def subscription(self, stanza):
        dbg("subscription:\n%s" % (fmt_evt(stanza), ), 3)

        send_response = not (stanza.get_type() == 'subscribed')
        if send_response:
            self.safe_send(stanza.make_accept_response())

        return True

    #
    # iq handlers
    #

    def vipadia_command(self, iq):
        dbg("vipadia_command:\n%s" % (fmt_evt(iq), ))

        items = iq.xpath_eval("v:command/v:item", {
            "v": "http://vipadia.com/skype",
        })
        for item in items:
            command = item.prop("command")
            if command == "message":
                ujid = JID(item.prop("ujid"))
                message = item.prop("message")

                dbg("  +ujid:%s precedingmessage:%s" % (
                    ujid.as_utf8(),
                    PrecedingMessage,
                ))
                if ujid in PrecedingMessage and PrecedingMessage[
                        ujid] == message:
                    continue

                PrecedingMessage[ujid] = message
                self.safe_send(Message(to_jid=ujid, body=message))
                dbg("  -ujid:%s precedingmessage:%s" % (
                    ujid.as_utf8(),
                    PrecedingMessage,
                ))

        return True
Пример #27
0
            self.stream.send(
                Message(to_jid=target, body=unicode("Teścik", "utf-8")))

    def post_disconnect(self):
        print "Disconnected"
        raise Disconnected


logger = logging.getLogger()
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

libxml2.debugMemory(1)

print "creating stream..."
s = MyClient(jid=JID("test@localhost/Test"),
             password=u"123",
             auth_methods=["sasl:DIGEST-MD5", "digest"])

print "connecting..."
s.connect()

print "processing..."
try:
    try:
        s.loop(1)
    finally:
        s.disconnect()
except KeyboardInterrupt:
    traceback.print_exc(file=sys.stderr)
except (StreamError, Disconnected), e:
Пример #28
0
    def message(self, stanza):
        dbg(
            "message:\nfrm:%s to:%s" % (
                stanza.get_from().as_utf8(),
                stanza.get_to().as_utf8(),
            ), 3)
        global RegDB

        body = stanza.get_body()
        frm = stanza.get_from()
        user = stanza.get_from().bare().as_utf8()

        ujid = JID(user)
        dbg("  ++ujid:%s precedingmessage:%s" % (
            ujid.as_utf8(),
            PrecedingMessage,
        ))
        if ujid in PrecedingMessage: del PrecedingMessage[ujid]
        dbg("  --ujid:%s precedingmessage:%s" % (
            ujid.as_utf8(),
            PrecedingMessage,
        ))

        if body:
            cmd = body.split()
            if len(cmd) > 0:
                reply = ""
                if cmd[0].lower() == "register":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"

                    skypeuser = cmd[1]
                    skypepass = cmd[2]

                    RegDB.remove_credentials(user)
                    RegDB.set_credentials_plain(user, skypeuser, skypepass)

                    reply = "Registration successful for " + skypeuser
                    message = Message(to_jid=stanza.get_from(), body=reply)
                    self.safe_send(message)

                    sub = Iq(to_jid=self.config.master, stanza_type="set")
                    query = sub.new_query('http://vipadia.com/skype',
                                          "command")
                    add_child(query,
                              "item",
                              attrs={
                                  "command": "register-available",
                                  "jid": frm.as_utf8()
                              })
                    dbg("  sub:\n%s" % (fmt_evt(sub), ))
                    self.safe_send(sub)
                    reply = "Presence request sent"

                elif cmd[0].lower() == "register-carrier":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"

                    skypeuser = cmd[1]
                    ## KeyCzar
                    ##                     crypter = keyczar.Encrypter.Read(PUBLIC_KEYLOC)
                    skypesecret = cmd[2]
                    ## KeyCzar
                    ##                     skypesecret = crypter.Encrypt(str(skypesecret))

                    spawn = Iq(to_jid=self.config.master, stanza_type="set")
                    command = spawn.new_query("http://vipadia.com/skype",
                                              "command")
                    add_child(command,
                              "item",
                              attrs={
                                  "command": "spawn",
                                  "ujid": frm.as_utf8(),
                                  "skypeuser": skypeuser,
                                  "skypesecret": skypesecret,
                              })
                    self.safe_send(spawn)

                elif cmd[0].lower() == "unregister":
                    if len(cmd) == 1:
                        RegDB.remove_credentials(user)
                        reply = "Unregistration successful"

                else:
                    reply = "Skype Registration Commands:\r\n" + \
                    " register <skypeuser> <skypepass>\r\n" + \
                    " unregister"

                message = Message(to_jid=stanza.get_from(), body=reply)
                self.safe_send(message)

        return True
Пример #29
0
    openlog()
    log(" ".join(sys.argv))
    
    locale.setlocale(locale.LC_CTYPE, "")
    encoding = locale.getlocale()[1]
    if not encoding: encoding = "us-ascii"
    sys.stdout = codecs.getwriter(encoding)(sys.stdout, errors="replace")
    sys.stderr = codecs.getwriter(encoding)(sys.stderr, errors="replace")

    args = base64.b64decode(sys.argv[1]).split("\0")
    dbg("  args:[%d] %s" % (len(args), args,))

    jid, secret, skypeuser, skypesecret, xmppujid, \
         Mode, Master, Muc, Slave, Marketing_message = args
    
    jid = JID(jid)
    xmppujid = JID(xmppujid)
    
    logger = logging.getLogger()
    logger.addHandler(logging.FileHandler("/tmp/bundle-%s.log" % jid.resource))
    logger.setLevel(logging.DEBUG) # change to DEBUG for higher verbosity

    try:
        log("bundle: jid:%s xmppujid:%s" % (jid.as_utf8(), xmppujid.as_utf8()))
        Bundle = SkypeBundle(jid, secret, skypeuser, skypesecret, xmppujid)

        attempts = 0
        keepalive = Iq(to_jid=Slave, stanza_type="set")
        keptalive = 0
        while Bundle.running:
            try:
Пример #30
0
# PyXMPP uses `logging` module for its debug output
# applications should set it up as needed
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO) # change to DEBUG for higher verbosity

if len(sys.argv) < 3:
    print u"Usage:"
    print "\t%s JID password ['tls_noverify'|cacert_file]" % (sys.argv[0],)
    print "example:"
    print "\t%s test@localhost verysecret" % (sys.argv[0],)
    sys.exit(1)

print u"creating client..."

c=Client(JID(sys.argv[1]), sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else None)

print u"connecting..."
c.connect()

print u"looping..."
try:
    # Component class provides basic "main loop" for the applitation
    # Though, most applications would need to have their own loop and call
    # component.stream.loop_iter() from it whenever an event on
    # component.stream.fileno() occurs.
    c.loop(1)
except IOError, e:
    if e.errno == errno.EPIPE:
    # IGNORE EPIPE error
        print "PIPE ERROR -- IGNORING"
Пример #31
0
    def vipadia_command(self, iq):
        dbg("vipadia_command:\n%s" % (fmt_evt(iq),))
        StLock.acquire()
        try:
            items = iq.xpath_eval("v:command/v:item", { "v": "http://vipadia.com/skype", })
            for item in items:
                command = item.prop("command")
                if command == "subscribe":
                    djid = JID(item.prop("djid"))

                    if djid not in St['dialbacks']:
                        self.safe_send(iq.make_result_response())
                        return True

                    self.safe_send(Presence(
                        to_jid=St['dialbacks'][djid], from_jid=item.prop("from"),
                        stanza_type="subscribe"))

                elif command == "subscribed":
                    frm = JID("%s@%s" % (item.prop("from"), self.config.component))

                    ujid = St['dialbacks'][get_from(iq)]
                    self.safe_send(Presence(
                        to_jid=ujid, from_jid=frm, stanza_type="subscribed"))

                elif command == "register-subscribe":
                    jid = JID(item.prop("jid"))
                    self.safe_send(Presence(
                        to_jid=jid.bare(), from_jid=self.config.component, stanza_type="subscribe"))

                elif command == "register-available":
                    jid = JID(item.prop("jid"))
                    fake_available = Presence(to_jid=self.config.component, from_jid=jid)
                    self.presence_available(fake_available)

                elif command == "out-subscribe":
                    frm = JID("%s@%s" % (item.prop("from"), self.config.component))

                    iq_frm = get_from(iq)
                    if iq_frm not in St['dialbacks']:
                        self.safe_send(iq.make_result_response())
                        return True

                    ujid = St['dialbacks'][iq_frm]
                    self.safe_send(Presence(
                        to_jid=ujid, from_jid=frm, stanza_type="subscribe"))                

                elif command == "slave-online":
                    frm = get_from(iq)
                    digest = str(item.prop("digest"))
                    if not self.is_valid_slave(frm.as_utf8(), digest):
                        err("invalid slave!  frm:%s iq:\n%s" % (frm.as_utf8(), fmt_evt(iq)))
                        self.safe_send(iq.make_error_response("forbidden"))
                        return True

                    capacity = int(item.prop("capacity"))
                    base = int(item.prop("base"))

                    St['slaves'][frm] = None                
                    St['slots'][frm] = {}
                    dbg("  before St['slots']:%s" % (St['slots'],))
                    for i in range(base, base+capacity):
                        if i not in St['slots'][frm]: St['slots'][frm][i] = None
                    dbg("  after St['slots']:%s" % (St['slots'],))

                    self.safe_send(Presence(
                        to_jid=frm, from_jid=self.config.component, stanza_type="subscribe"))

                elif command == "spawn":
                    ujid = item.prop("ujid")
                    skypeuser = item.prop("skypeuser")
                    skypesecret = item.prop("skypesecret")
                    
                    errstr = self._spawn(JID(ujid), skypeuser, skypesecret)
                    if errstr: err("_spawn error!  errstr:%s" % (errstr,))

                else:
                    err("unknown command!  command:%s\n%s" % (command, fmt_evt(iq),))
                    self.safe_send(iq.make_error_response("feature-not-implemented"))
                    return True

            self.safe_send(iq.make_result_response())
            return True
        finally:
            StLock.release()
Пример #32
0
if len(sys.argv) == 1:
    nick = getuser()
    print notify(
        '!', 'y',
        "Assuming you are %s\nIf this is wrong, pass your nick as the first parameter"
        % nick)
else:
    nick = sys.argv[1]

if ROOM_TYPE == 'MUC':
    jidname = nick + '@' + DOMAIN
else:
    sys.exit(notify('!', 'r', "%s is not supported yet" % ROOM_TYPE))

while True:
    c = CLIClient(JID(jidname), getpass(), nick)
    print "Connecting..."
    c.connect()

    try:
        loop(c)
    except SASLAuthenticationFailed:
        print "Authentication failed. Try again."
    except KeyboardInterrupt:
        print "Disconnecting..."
        c.disconnect()
        break
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
# vi: sts=4 et sw=4
Пример #33
0
 def session_started(self):
     self._session_started_helper(EvalRoomHandler(), JID(ROOM, SERVER))
Пример #34
0
class SkypeSlave(JabberClient):
    def __init__(self, config):
        self.config = config
        self.running = True
        self.connection = CONNECTION.idle

        self.jid = JID("%s@%s/slave" % (
            config.slave,
            config.domain,
        ))
        log("slave: jid:%s" % (self.jid.as_utf8(), ))

        tls = streamtls.TLSSettings(require=True, verify_peer=False)
        auth = ['digest']

        JabberClient.__init__(self,
                              self.jid,
                              self.config.secret,
                              disco_name="Vipadia Skype Gateway Slave",
                              disco_type="bot",
                              tls_settings=tls,
                              auth_methods=auth)

    def safe_send(self, stanza):
        to = stanza.get_to()
        if not to.domain.endswith(self.config.domain): to = to.bare()

        stanza = Stanza(stanza, to_jid=to)
        dbg("tx:\n%s" % (fmt_evt(stanza), ))
        self.stream.send(stanza)

    def stream_state_changed(self, state, arg):
        dbg("stream_state_changed: %s %r" % (state, arg), 3)

    def session_started(self):
        log("session_started: jid:%s" % (self.jid.as_utf8(), ))

        self.connection = CONNECTION.connected
        JabberClient.session_started(self)

        self.stream.set_presence_handler("subscribe", self.subscribe)
        self.stream.set_iq_set_handler("query", "http://vipadia.com/skype",
                                       self.vipadia_iq)

        self.slave_online()

    def slave_online(self):
        slavejid = JID("%s@%s/slave" % (self.config.slave, self.config.domain))
        iq = Iq(to_jid=self.config.master,
                from_jid=slavejid,
                stanza_type="set")
        command = iq.new_query('http://vipadia.com/skype', "command")
        digest = generate_slave_digest(str(slavejid.as_utf8()),
                                       self.config.slave_secret)
        add_child(command,
                  "item",
                  attrs={
                      "command": "slave-online",
                      "capacity": self.config.capacity,
                      "base": self.config.base,
                      "digest": digest
                  })
        dbg("  iq:\n%s" % (fmt_evt(iq), ))
        self.safe_send(iq)

    def disconnected(self):
        log("slave disconnected! jid:%s" % (self.jid.as_utf8(), ))
        self.connection = CONNECTION.error

    def subscribe(self, presence):
        dbg("subscribe: presence:\n%s" % (fmt_evt(presence), ))

        resp = presence.make_accept_response()
        dbg("  resp:\n%s" % (fmt_evt(resp), ))
        self.safe_send(resp)

    def vipadia_iq(self, iq):
        dbg("vipadia_iq:\n%s" % (fmt_evt(iq), ), 3)

        items = iq.xpath_eval("v:query/v:item", {
            "v": "http://vipadia.com/skype",
        })
        for item in items:
            jid = JID(item.prop("dialback"))
            (_, screen, _) = jid.resource.split(":")
            secret = item.prop("secret")
            skypeuser = item.prop("skypeuser")
            skypesecret = item.prop("skypesecret")
            xmppujid = item.prop("xmppujid")
            mode = item.prop("mode")
            marketing_message = item.prop("marketing-message")

            argstring = base64.b64encode(
                "%s\0%s\0%s\0%s\0%s\0%s\0%s\0%s\0%s\0%s" % (
                    jid.as_utf8(),
                    secret,
                    skypeuser,
                    skypesecret,
                    xmppujid,
                    mode,
                    self.config.master,
                    self.config.muc,
                    "%s@%s" % (self.config.slave, self.config.domain),
                    marketing_message,
                ))
            cmd = ["./karaka/bundle.sh", screen, argstring]
            dbg("  cmd:%s" % (cmd, ))
            ps = subprocess.Popen(cmd, stdout=subprocess.PIPE)

        return True
Пример #35
0
    def vipadia_command(self, iq):
        dbg("vipadia_command:\n%s" % (fmt_evt(iq), ))
        StLock.acquire()
        try:
            items = iq.xpath_eval("v:command/v:item", {
                "v": "http://vipadia.com/skype",
            })
            for item in items:
                command = item.prop("command")
                if command == "subscribe":
                    djid = JID(item.prop("djid"))

                    if djid not in St['dialbacks']:
                        self.safe_send(iq.make_result_response())
                        return True

                    self.safe_send(
                        Presence(to_jid=St['dialbacks'][djid],
                                 from_jid=item.prop("from"),
                                 stanza_type="subscribe"))

                elif command == "subscribed":
                    frm = JID("%s@%s" %
                              (item.prop("from"), self.config.component))

                    ujid = St['dialbacks'][get_from(iq)]
                    self.safe_send(
                        Presence(to_jid=ujid,
                                 from_jid=frm,
                                 stanza_type="subscribed"))

                elif command == "register-subscribe":
                    jid = JID(item.prop("jid"))
                    self.safe_send(
                        Presence(to_jid=jid.bare(),
                                 from_jid=self.config.component,
                                 stanza_type="subscribe"))

                elif command == "register-available":
                    jid = JID(item.prop("jid"))
                    fake_available = Presence(to_jid=self.config.component,
                                              from_jid=jid)
                    self.presence_available(fake_available)

                elif command == "out-subscribe":
                    frm = JID("%s@%s" %
                              (item.prop("from"), self.config.component))

                    iq_frm = get_from(iq)
                    if iq_frm not in St['dialbacks']:
                        self.safe_send(iq.make_result_response())
                        return True

                    ujid = St['dialbacks'][iq_frm]
                    self.safe_send(
                        Presence(to_jid=ujid,
                                 from_jid=frm,
                                 stanza_type="subscribe"))

                elif command == "slave-online":
                    frm = get_from(iq)
                    digest = str(item.prop("digest"))
                    if not self.is_valid_slave(frm.as_utf8(), digest):
                        err("invalid slave!  frm:%s iq:\n%s" %
                            (frm.as_utf8(), fmt_evt(iq)))
                        self.safe_send(iq.make_error_response("forbidden"))
                        return True

                    capacity = int(item.prop("capacity"))
                    base = int(item.prop("base"))

                    St['slaves'][frm] = None
                    St['slots'][frm] = {}
                    dbg("  before St['slots']:%s" % (St['slots'], ))
                    for i in range(base, base + capacity):
                        if i not in St['slots'][frm]:
                            St['slots'][frm][i] = None
                    dbg("  after St['slots']:%s" % (St['slots'], ))

                    self.safe_send(
                        Presence(to_jid=frm,
                                 from_jid=self.config.component,
                                 stanza_type="subscribe"))

                elif command == "spawn":
                    ujid = item.prop("ujid")
                    skypeuser = item.prop("skypeuser")
                    skypesecret = item.prop("skypesecret")

                    errstr = self._spawn(JID(ujid), skypeuser, skypesecret)
                    if errstr: err("_spawn error!  errstr:%s" % (errstr, ))

                else:
                    err("unknown command!  command:%s\n%s" % (
                        command,
                        fmt_evt(iq),
                    ))
                    self.safe_send(
                        iq.make_error_response("feature-not-implemented"))
                    return True

            self.safe_send(iq.make_result_response())
            return True
        finally:
            StLock.release()
Пример #36
0
class SkypeSlave(JabberClient):

    def __init__(self, config):
        self.config = config
        self.running = True
        self.connection = CONNECTION.idle
        
        self.jid = JID("%s@%s/slave" % (config.slave, config.domain,))
        log("slave: jid:%s" % (self.jid.as_utf8(),))
        
        tls = streamtls.TLSSettings(require=True, verify_peer=False)
        auth = [ 'digest' ]

        JabberClient.__init__(self, self.jid, self.config.secret,
            disco_name="Vipadia Skype Gateway Slave", disco_type="bot",
            tls_settings=tls, auth_methods=auth)
        
    def safe_send(self, stanza):
        to = stanza.get_to()
        if not to.domain.endswith(self.config.domain): to = to.bare()
            
        stanza = Stanza(stanza, to_jid=to)
        dbg("tx:\n%s" % (fmt_evt(stanza),))
        self.stream.send(stanza)

    def stream_state_changed(self, state, arg):
        dbg("stream_state_changed: %s %r" % (state, arg), 3)
        
    def session_started(self):
        log("session_started: jid:%s" % (self.jid.as_utf8(),))

        self.connection = CONNECTION.connected
        JabberClient.session_started(self)
        
        self.stream.set_presence_handler("subscribe", self.subscribe)
        self.stream.set_iq_set_handler(
            "query", "http://vipadia.com/skype", self.vipadia_iq)

        self.slave_online()
        
    def slave_online(self):
        slavejid = JID("%s@%s/slave" % (self.config.slave, self.config.domain))
        iq = Iq(to_jid=self.config.master, from_jid=slavejid, stanza_type="set")
        command = iq.new_query('http://vipadia.com/skype', "command")
        digest = generate_slave_digest(str(slavejid.as_utf8()),
                                       self.config.slave_secret)
        add_child(command, "item", attrs={ "command": "slave-online",
                                           "capacity": self.config.capacity,
                                           "base": self.config.base,
                                           "digest": digest
                                           })
        dbg("  iq:\n%s" % (fmt_evt(iq),))
        self.safe_send(iq)
        
    def disconnected(self):
        log("slave disconnected! jid:%s" % (self.jid.as_utf8(),))
        self.connection = CONNECTION.error

    def subscribe(self, presence):
        dbg("subscribe: presence:\n%s" % (fmt_evt(presence),))

        resp = presence.make_accept_response()
        dbg("  resp:\n%s" % (fmt_evt(resp),))
        self.safe_send(resp)
        
    def vipadia_iq(self, iq):
        dbg("vipadia_iq:\n%s" % (fmt_evt(iq),), 3)

        items = iq.xpath_eval("v:query/v:item", { "v": "http://vipadia.com/skype", })
        for item in items:
            jid = JID(item.prop("dialback"))
            (_, screen, _) = jid.resource.split(":")
            secret = item.prop("secret")
            skypeuser = item.prop("skypeuser")
            skypesecret = item.prop("skypesecret")
            xmppujid = item.prop("xmppujid")
            mode = item.prop("mode")
            marketing_message = item.prop("marketing-message")

            argstring = base64.b64encode(
                "%s\0%s\0%s\0%s\0%s\0%s\0%s\0%s\0%s\0%s" % (
                jid.as_utf8(), secret,
                skypeuser, skypesecret, xmppujid,
                mode, self.config.master, self.config.muc,
                "%s@%s" % (self.config.slave, self.config.domain),
                marketing_message,
                ))
            cmd = [ "./karaka/bundle.sh", screen, argstring ] 
            dbg("  cmd:%s"  % (cmd,))
            ps = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        
        return True
# PyXMPP uses `logging` module for its debug output
# applications should set it up as needed
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)  # change to DEBUG for higher verbosity

if len(sys.argv) < 3:
    print u"Usage:"
    print "\t%s JID password ['tls_noverify'|cacert_file]" % (sys.argv[0], )
    print "example:"
    print "\t%s test@localhost verysecret" % (sys.argv[0], )
    sys.exit(1)

print u"creating client..."

c = Client(JID(sys.argv[1]), sys.argv[2],
           sys.argv[3] if len(sys.argv) > 3 else None)

print u"connecting..."
c.connect()

print u"looping..."

driver_cleverbot = webdriver.Firefox()

try:
    # Component class provides basic "main loop" for the applitation
    # Though, most applications would need to have their own loop and call
    # component.stream.loop_iter() from it whenever an event on
    # component.stream.fileno() occurs.
    c.loop(1)
Пример #38
0
    def vipadia_command(self, iq):
        dbg("vipadia_command:\n%s" % (fmt_evt(iq), ))
        StLock.acquire()
        try:
            items = iq.xpath_eval("v:command/v:item", {
                "v": "http://vipadia.com/skype",
            })
            for item in items:
                command = item.prop("command")
                if command == "create-muc":
                    chatid = item.prop("chatid")  # skype chat name
                    jid = JID(item.prop("jid"))
                    member = item.prop("member")

                    gid = groupchatid(chatid)

                    # populate St['conferences']
                    St['conferences'][gid] = (iq.get_from(), jid)

                    invite = Message(
                        from_jid="%s@%s" % (gid, self.config.muc),
                        to_jid=jid,
                    )
                    x = invite.add_new_content(
                        "http://jabber.org/protocol/muc#user", "x")
                    add_child(add_child(x,
                                        "invite",
                                        attrs={
                                            "from":
                                            "%s@%s" %
                                            (member, self.config.component)
                                        }),
                              "reason",
                              value=Msgs.join_chat)
                    add_child(x, "password")
                    self.safe_send(invite)

                    result = iq.make_result_response()
                    q = result.new_query("http://vipadia.com/skype", "command")
                    add_child(q,
                              "item",
                              attrs={
                                  "command": "create-muc",
                                  "gid": gid,
                                  "chatid": chatid
                              })
                    self.safe_send(result)

                elif command == "destroy-muc":
                    gid = item.prop("gid")  # skype chat name
                    if gid in St['conferences']:
                        # Tidy up
                        del St['conferences'][gid]

                        result = iq.make_result_response()
                        q = result.new_query("http://vipadia.com/skype",
                                             "command")
                        add_child(q,
                                  "item",
                                  attrs={
                                      "command": "destroy-muc",
                                      "gid": gid
                                  })

                        self.safe_send(result)

                else:
                    err("unknown command!  command:%s\n%s" % (
                        command,
                        fmt_evt(iq),
                    ))

            return True
        finally:
            StLock.release()
Пример #39
0
    if not m: return
    to_eval = m.group(1).encode('ascii', 'ignore')
    try:
        if lang == 'python':
            return str(eval(to_eval))
        elif lang == 'perl':
            to_eval = to_eval.replace('/', '\/').replace('`', '')
            return runpipe('perl', 'print (%s),"\\n"' % to_eval)
        elif lang == 'ruby':
            to_eval = to_eval.replace('/', '\/').replace('`', '')
            return runpipe('ruby', 'puts (%s)' % to_eval)
        elif lang == 'haskell':
            return runpipe('ghci -v0', to_eval)

        return "%s(%s)" % (lang, to_eval)
    except Exception, e:
        return str(e)


mucroombot.setup_localization()
if ROOM_TYPE == 'MUC':
    jidname = getuser() + '@' + DOMAIN
    mk_client = lambda: MucEvalClient(JID(jidname), getpass(), BOT_NAME)
    while mucroombot.main(mk_client):
        pass
elif ROOM_TYPE == 'IRC':
    mk_client = lambda: IrcEvalClient(BOT_NAME)
    while ircbot.main(mk_client):
        pass
# vi: sts=4 et sw=4
Пример #40
0
if options.database_host and options.database and options.database_user and options.database_password:
    print("Connecting to the database")
    dbh = PgSQL.connect(host=options.database_host,
                        user=options.database_user, password=options.database_password)
    dbh.autocommit = 1
    cursor = dbh.cursor()
else:
    print("Not connecting to the database, are you sure?")
    dbh = None

if not options.files:
    print("Not storing files, are you sure?")

while True:
    print(u"creating client... %s" % options.resource)
    c=Client(JID(options.username + '/' + options.resource),options.password)

    print(u"connecting...")
    c.connect()

    print(u"looping...")
    try:
        # Component class provides basic "main loop" for the applitation
        # Though, most applications would need to have their own loop and call
        # component.stream.loop_iter() from it whenever an event on
        # component.stream.fileno() occurs.
        c.loop(1)
        c.idle()
    except KeyboardInterrupt:
        print(u"disconnecting...")
        c.disconnect()
Пример #41
0
class _Register(JabberClient):

    def __init__(self, config):
        self.config = config
        self.connection = CONNECTION.idle
        self.running = True
        
        self.jid = JID("%s@%s/%s" % (config.register, config.domain, config.register))
        log("register: jid:%s" % (self.jid.as_utf8(),))
        
        tls = streamtls.TLSSettings(require=True, verify_peer=False)
        auth = [ 'digest' ]

        JabberClient.__init__(self, self.jid, self.config.secret,
            disco_name="Vipadia Skype Gateway Register", disco_type="bot",
            tls_settings=tls, auth_methods=auth)
        
    def stream_state_changed(self, state, arg):
        dbg("stream_state_changed: %s %r" % (state, arg), 3)
        
    def safe_send(self, stanza):
        to = stanza.get_to()
        if not to.domain.endswith(self.config.domain): to = to.bare()
            
        stanza = Stanza(stanza, to_jid=to)
        dbg("tx:\n%s" % (fmt_evt(stanza),))
        self.stream.send(stanza)

    def session_started(self):
        log("session_started: jid:%s" % (self.jid.as_utf8(),))

        self.connection = CONNECTION.connected
        JabberClient.session_started(self)

        self.stream.set_message_handler("normal", self.message)
        self.stream.set_presence_handler("subscribe", self.subscription)
        self.stream.set_iq_set_handler(
            "command", "http://vipadia.com/skype", self.vipadia_command)

        global Connected
        Connected = True

        self.safe_send(Presence(to_jid=self.config.master, stanza_type="subscribe"))

    #
    # message handler
    #
    
    def message(self, stanza):
        dbg("message:\nfrm:%s to:%s" % (
            stanza.get_from().as_utf8(), stanza.get_to().as_utf8(),), 3)
        global RegDB
        
        body = stanza.get_body()
        frm = stanza.get_from()
        user = stanza.get_from().bare().as_utf8()

        ujid = JID(user)
        dbg("  ++ujid:%s precedingmessage:%s" % (ujid.as_utf8(), PrecedingMessage,))
        if ujid in PrecedingMessage: del PrecedingMessage[ujid]
        dbg("  --ujid:%s precedingmessage:%s" % (ujid.as_utf8(), PrecedingMessage,))
                                                               
        if body:         
            cmd = body.split()
            if len(cmd) > 0 :
                reply = ""
                if cmd[0].lower() == "register":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"

                    skypeuser = cmd[1]
                    skypepass = cmd[2]
                    
                    RegDB.remove_credentials(user)
                    RegDB.set_credentials_plain(user, skypeuser, skypepass)
                                                                     
                    reply = "Registration successful for " + skypeuser
                    message = Message(to_jid=stanza.get_from(), body=reply)
                    self.safe_send(message)

                    sub = Iq(to_jid=self.config.master, stanza_type="set")
                    query = sub.new_query('http://vipadia.com/skype', "command")
                    add_child(query, "item", attrs={ "command" : "register-available",
                                                     "jid": frm.as_utf8() })
                    dbg("  sub:\n%s" % (fmt_evt(sub),))
                    self.safe_send(sub)
                    reply = "Presence request sent"

                elif cmd[0].lower() == "register-carrier":
                    if len(cmd) != 3:
                        reply = "error, please use: register <skypeuser> <skypepassword>"
                        
                    skypeuser = cmd[1]
                    ## KeyCzar
##                     crypter = keyczar.Encrypter.Read(PUBLIC_KEYLOC)
                    skypesecret = cmd[2]
                    ## KeyCzar
##                     skypesecret = crypter.Encrypt(str(skypesecret))
                    
                    spawn = Iq(to_jid=self.config.master, stanza_type="set")
                    command = spawn.new_query("http://vipadia.com/skype", "command")
                    add_child(command, "item", attrs={ "command": "spawn",
                                                       "ujid": frm.as_utf8(),
                                                       "skypeuser": skypeuser,
                                                       "skypesecret": skypesecret,
                                                       })
                    self.safe_send(spawn)
                    
                elif cmd[0].lower() == "unregister":
                    if len(cmd) == 1:
                        RegDB.remove_credentials(user)
                        reply = "Unregistration successful"

                else:
                    reply = "Skype Registration Commands:\r\n" + \
                    " register <skypeuser> <skypepass>\r\n" + \
                    " unregister"
                
                message = Message(to_jid=stanza.get_from(), body=reply)
                self.safe_send(message)
        
        return True

    #
    # presence handlers
    #
    
    def subscription(self, stanza):
        dbg("subscription:\n%s" % (fmt_evt(stanza),), 3)
        
        send_response = not (stanza.get_type() == 'subscribed')
        if send_response:
            self.safe_send(stanza.make_accept_response())

        return True

    #
    # iq handlers
    #

    def vipadia_command(self, iq):
        dbg("vipadia_command:\n%s" % (fmt_evt(iq),))

        items = iq.xpath_eval("v:command/v:item", { "v": "http://vipadia.com/skype", })
        for item in items:
            command = item.prop("command")
            if command == "message":
                ujid = JID(item.prop("ujid"))
                message = item.prop("message")

                dbg("  +ujid:%s precedingmessage:%s" % (ujid.as_utf8(), PrecedingMessage,))
                if ujid in PrecedingMessage and PrecedingMessage[ujid] == message:
                    continue

                PrecedingMessage[ujid] = message
                self.safe_send(Message(to_jid=ujid, body=message))
                dbg("  -ujid:%s precedingmessage:%s" % (ujid.as_utf8(), PrecedingMessage,))

        return True