Example #1
0
    def presence_match(
            self, message):  # frm=None, type=None, status=None, show=None):

        frm, type, status, show, role, affiliation = message.frm, message.type, message.status, message.show, message.role, message.affiliation

        #if self._frm    !=None and frm    != self._frm:    return False
        if self._type is not None and type != self._type:
            return False
        if self._status is not None and status != self._status:
            return False
        if self._show is not None and show != self._show:
            return False
        if self._role is not None and role != self._role:
            return False
        if self._affiliation is not None and affiliation != self._affiliation:
            return False

        if self._frm:
            if not xmpp.JID(self._frm).getResource():
                if self._frm != xmpp.JID(frm).getBareJID():
                    return False
            else:
                if self._frm != frm:
                    return False

        return True
Example #2
0
    def testXMPPMessageMatchFalse(self):
        xmpptemplate = xmpp.Message()
        xmpptemplate.setFrom(xmpp.JID("sender1@host"))
        xmpptemplate.setTo(xmpp.JID("recv1@host"))

        message = xmpp.Message()
        message.setFrom(xmpp.JID("sender1@host"))
        message.setTo(xmpp.JID("recv2@host"))

        mt = spade.Behaviour.MessageTemplate(xmpptemplate)

        self.assertFalse(mt.match(message))
Example #3
0
 def invite(self, mess, args):
     """Invite a person to join the room. Works only if the person has added the bot as a friend, as of now."""
     user = self.get_sender_username(mess)
     if user in self.users:
         self.send(
             args,
             '%s invited you to join %s. Say ",help" to see how to join.' %
             (user, CHANNEL))
         self.invited['%s@%s' % (xmpp.JID(args).getNode(),
                                 xmpp.JID(args).getDomain())] = ''
         self.log.info('%s invited %s.' % (user, args))
         self.save_state()
         self.message_queue.append('_%s invited %s_' %
                                   (self.users[user], args))
Example #4
0
    def testXMPPIqMatchTrue(self):
        xmpptemplate = xmpp.Iq()
        xmpptemplate.setFrom(xmpp.JID("sender1@host"))
        xmpptemplate.setTo(xmpp.JID("recv1@host"))
        xmpptemplate.setType("set")

        message = xmpp.Iq()
        message.setFrom(xmpp.JID("sender1@host"))
        message.setTo(xmpp.JID("recv1@host"))
        message.setType("set")

        mt = spade.Behaviour.MessageTemplate(xmpptemplate)

        self.assertTrue(mt.match(message))
Example #5
0
    def park(self, vm_informations):
        """
        Park a virtual machine
        @type vm_informations: list
        @param vm_informations: list of dict like {"uuid": x, "status": y, "parker": z)}
        """
        vm_informations_cleaned = []
        for vm_info in vm_informations:
            if self.is_vm_parked(vm_info["uuid"]):
                self.entity.log.error("VMPARKING: VM with UUID %s is already parked" % vm_info["uuid"])
                continue

            vm = self.entity.get_vm_by_uuid(vm_info["uuid"])
            if not vm:
                self.entity.log.error("VMPARKING: No virtual machine with UUID %s" % vm_info["uuid"])
                continue
            if not vm.domain:
                self.entity.log.error("VMPARKING: VM with UUID %s cannot be parked because it is not defined" % vm_info["uuid"])
                continue
            vm_informations_cleaned.append(vm_info)

        # Now, perform operations
        for vm_info in vm_informations_cleaned:
            vm = self.entity.get_vm_by_uuid(vm_info["uuid"])
            if not vm.info()["state"] == 5:
                vm.destroy()
            domain = vm.xmldesc(mask_description=False)
            vm_jid = xmpp.JID(domain.getTag("description").getData().split("::::")[0])
            self.set_vms_status([vm_info])
            self.entity.soft_free(vm_jid)
        self.entity.push_change("vmparking", "parked")
Example #6
0
class Bot:
    def message_handler(connect_object, message_node):
        command1 = str(unicode(message_node.getBody()).encode('utf-8'))
        command2 = str(message_node.getFrom().getStripped())

        #the fun begins from this place..
        connect_object.send(xmpp.Message(command2, (k.respond(command1))))
        b = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        a.write(str(b) + " " + command2 + " >>> " + k.respond(command1) + "\n")

    jid = xmpp.JID(user)
    connection = xmpp.Client(server)
    connection.connect()
    result = connection.auth(jid.getNode(), passwd)
    connection.RegisterHandler('message', message_handler, "")
    connection.RegisterHandler('presence', presence_handler, "")
    connection.sendInitPresence()
    press = xmpp.Presence()
    press.setStatus(
        "Hi from bot...i will chat with you and tell you new things you might like"
    )
    connection.send(press)

    while (1):
        connection.Process(1)
Example #7
0
    def delete(self, uuid, push=True):
        """
        Delete a parked virtual machine
        @type uuid: String
        @param uuid: the UUID of a parked VM
        @type push: Boolean
        @param push: if False, do not push changes
        """
        if not self.is_vm_already_parked(uuid):
            raise Exception(
                "There is no virtual machine parked with ticket %s" % ticket)

        vm_item = self.get_vm_by_uuid_from_db(uuid)
        self.remove_vm_from_db(uuid)
        vmjid = xmpp.JID(
            vm_item["domain"].getTag("description").getData().split("::::")[0])
        vmfolder = "%s/%s" % (self.configuration.get(
            "VIRTUALMACHINE", "vm_base_path"), vmjid.getNode())
        if os.path.exists(vmfolder):
            shutil.rmtree(vmfolder)
        self.entity.get_plugin("xmppserver").users_unregister([vmjid])
        if push:
            self.entity.push_change("vmparking", "deleted")
        self.entity.log.info(
            "VMPARKING: successfully deleted %s from parking" % str(vmjid))
Example #8
0
    def unregister_vms(self, entries):
        """
        Unregister a list of vms from central db.
        @type entries: List
        @param entries: list of vms
        """
        # first, we extract jid so that the hypervisor can unregister them
        uuids = []
        for entry in entries:
            uuids.append(entry["uuid"])
        where_statement = "uuid = '"
        where_statement += "' or uuid='".join(uuids)
        where_statement += "'"

        # list of vms which have been found in central db, including uuid and jid
        cleaned_entries = self.read_vms("uuid,domain", where_statement)
        for i in range(len(cleaned_entries)):
            domain_xml = cleaned_entries[i]["domain"]
            if domain_xml != "None":
                domain = xmpp.simplexml.NodeBuilder(
                    data=cleaned_entries[i]["domain"]).getDom()
                cleaned_entries[i]["jid"] = xmpp.JID(
                    domain.getTag("description").getData().split("::::")[0])
                del (cleaned_entries[i]["domain"])

        self.db_commit("delete from vms where uuid=:uuid", cleaned_entries)
        return cleaned_entries
Example #9
0
def start_bot():
    if len(sys.argv) < 3:
        print "Usage: start_bot.py [email protected] password"
    else:
        jid = xmpp.JID(sys.argv[1])
        user, server, password = jid.getNode(), jid.getDomain(), sys.argv[2]

        conn = xmpp.Client(server)  #,debug=[])
        conres = conn.connect()
        if not conres:
            print "Unable to connect to server %s!" % server
            sys.exit(1)
        if conres <> 'tls':
            print "Warning: unable to estabilish secure connection - TLS failed!"
        authres = conn.auth(user, password)
        if not authres:
            print "Unable to authorize on %s - check login/password." % server
            sys.exit(1)
        if authres <> 'sasl':
            print "Warning: unable to perform SASL auth os %s. Old authentication method used!" % server
        conn.RegisterHandler('message', messageCB)
        conn.RegisterHandler('presence', presenceCB)
        conn.sendInitPresence()
        ##conn.send(xmpp.protocol.Message('*****@*****.**','This is a automatic message'))

        print "Bot started."
        GoOn(conn)
Example #10
0
    def __init__(self, JID, Password):
        """ Create a new bot. Connect to the server and log in. """

        # connect...
        jid = xmpp.JID(JID)
        self.connection = xmpp.Client(jid.getDomain(), debug=[])
        self.en_ml_db = None
        result = self.connection.connect()

        if result is None:
            raise ConnectionError

        # authorize
        result = self.connection.auth(jid.getNode(), Password)

        if result is None:
            raise AuthorizationError

        self.connection.RegisterHandler('presence', self.presenceHandler)
        self.connection.RegisterHandler('message', self.messageHandler)
        # ...become available
        self.connection.sendInitPresence()
        # presence
        #self.connection.sendInitPresence(requestRoster=0)
        try:
            #search the dictionary in same directory of program
            self.en_ml_db = DictDB("freedict-eng-mal")
        except:
            #retry in standard directory of dictd
            self.en_ml_db = DictDB("/usr/share/dictd/freedict-eng-mal")
Example #11
0
    def __connect(self):
        self._jid = xmpp.JID(self._settings.jid)
        if not self._conn:
            if not self._options.debug:
                conn = xmpp.Client(self._jid.getDomain())
            else:
                conn = xmpp.Client(self._jid.getDomain(), debug=[])
            res = conn.connect()
            if not res:
                logging.error("Unable to connect to server %s." %
                              self._jid.getDomain())
                exit()
            if res <> 'tls':
                logging.warning("Unable to establish TLS connection.")

            res = conn.auth(self._jid.getNode(), self._settings.password,
                            self._settings.chat_name)
            if not res:
                logging.error("Unable to authenticate this connection.")
                exit()
            if res <> 'sasl':
                logging.warning("Unable to get SASL creditential for: %s." %
                                self.jid.getDomain())
            conn.RegisterHandler('message', self.message_handler)
            conn.RegisterHandler('presence', self.presence_handler)
            conn.sendInitPresence()
            self.roster = conn.Roster.getRoster()
            self._conn = conn
            if hasattr(self._settings, 'default_status'):
                self._conn.send(
                    xmpp.Presence(status=self._settings.default_status))
            if hasattr(self._settings, 'groupchat'): self.__join_muc()
Example #12
0
    def __init__(self, username, password, res=None):
        """Initializes the jabber bot and sets up commands."""
        self.__username = username
        self.__password = password
        self.__finished = False
        self.__status = None
        self.__seen = {}
        self.__threads = {}

        self.log = logging.getLogger(__name__)
        self.jid = xmpp.JID(self.__username)
        self.res = (res or self.__class__.__name__)
        self.conn = None
        self.roster = None
        self.commands = {}
        self.xmpp_debug = []
        self.reconnecting = False
        self.ignore_offline = False

        self.on_connect = no_fn
        self.on_reconnect = no_fn
        self.on_disconnect = no_fn

        for name, value in inspect.getmembers(self):
            if (inspect.ismethod(value)
                    and getattr(value, '_jabberbot_command', False)):

                name = getattr(value, '_jabberbot_command_name')
                self.log.debug('Registered command: %s' % name)
                self.commands[name] = value
Example #13
0
    def _init(self, debug):
        self._inbox = Queue(self.store.xmpp.inbox, self.log)
        self._outbox = Queue(self.store.xmpp[self.config["xmpp"]["user"]],
                             self.log)
        #self._inbox.clear()
        self._outbox.timeout(-1)

        JID = xmpp.JID(self.user)
        self.connection = xmpp.Client(JID.getDomain(), debug=debug)
        server = self.config["xmpp"]["server"]
        port = int(self.config["xmpp"]["port"])
        if self.connection.connect((server, port)) == '':
            self.log.error('Cannot connect to server %s port %d' %
                           (server, port))
            sys.exit(1)

        if self.connection.auth(JID.getNode(), self.token,
                                self.user + '-') == None:
            self.log.error('Authentication %s failed!' % self.user)
            sys.exit(1)

        self.connection.RegisterDisconnectHandler(
            self.connection.reconnectAndReauth())
        self.connection.RegisterHandler('message', self.receive)
        self.connection.getRoster()
        self.connection.sendInitPresence()
Example #14
0
 def is_bot_owner(self, room, nick):
     # проверка на уровень доступа овнера
     #FIXME: может не работать на полностью анонимных серверах
     if not self.in_roster(room, nick): return False
     jid = self.roster[room][nick][ROSTER_JID]
     if jid != None: jid = xmpp.JID(jid).getStripped().lower()
     return jid in self.configuration['bot_owners']
Example #15
0
    def connect(self):
        server = "gmail.com"
        jid = xmpp.JID(self.user)
        self.connection = xmpp.Client(server, debug=[])
        print "Connecting.."
        server = ('talk.google.com', 5223)
        if not self.connection.connect(server):
            self.emit(
                QtCore.SIGNAL("error"),
                "<b>Connection Error!</b><br>Check your internet connection")
            return False
        print "Connected!"

        result = self.connection.auth(jid.getNode(), self.password,
                                      self.appResource)
        if not result:
            self.emit(
                QtCore.SIGNAL("error"),
                "<b>Authentication Error!</b><br>Check your username and password"
            )
            return False

        self.connection.RegisterHandler('message', self.receiveHandler)
        self.connection.RegisterHandler('presence', self.presenceHandler)
        self.connection.sendInitPresence()
        self.setStatus("Scribbling in Colors")
        self.roster = self.connection.getRoster()
        self.emit(QtCore.SIGNAL("connected"), True)
        return True
Example #16
0
    def _initial_vars(self, *args, **kwargs):
        super(XMPP_Client, self)._initial_vars(*args, **kwargs)
        self._xmpp_id = kwargs.get('id', None)
        self._password = kwargs.get('password', None)
        self._server = kwargs.get('server', None)
        self._port = kwargs.get('port', None)

        if not self._xmpp:
            self._logger.info(
                'Connecting to server for id:{id} ({server})'.format(
                    id=self._xmpp_id,
                    server=self._server,
                ))
            status = None
            jid = xmpp.JID(self._xmpp_id)
            self._xmpp = xmpp.Client(jid.getDomain())
            self.connect()
            self._logger.info("Connection Result: {0}".format(status))
            result = self._xmpp.auth(
                re.match('(.*)\@.*', self._xmpp_id).group(1), self._password,
                'TESTING')
            #self._xmpp.sendInitPresence()
            self._logger.debug('Processing' + str(result))
        else:
            self._logger.debug('Here twice?')
Example #17
0
    def unpark(self, vm_informations):
        """
        Unpark virtual machine
        @type vm_informations: list
        @param vm_informations: list of dict like {"uuid": x, "status": y, "start": True|False, "parker": z}
        """
        vm_informations_cleaned = []
        # First, check if everything is correct and cleanup bad items
        for vm_info in vm_informations:
            if self.is_vm_parked(vm_info["uuid"]):
                vm_informations_cleaned.append(vm_info)
            else:
                self.entity.log.error("VMPARKING: There is no virtual machine parked with uuid %s" % vm_info["uuid"])

        # Now, perform operations
        for vm_info in vm_informations_cleaned:
            vm_item = self.get_vm_by_uuid_from_db(vm_info["uuid"])
            domain = vm_item["domain"]
            ret = str(domain).replace('xmlns=\"archipel:hypervisor:vmparking\"', '')
            domain = xmpp.simplexml.NodeBuilder(data=ret).getDom()
            vmjid = domain.getTag("description").getData().split("::::")[0]
            vmpass = domain.getTag("description").getData().split("::::")[1]
            vmname = domain.getTag("name").getData()
            vm_thread = self.entity.soft_alloc(xmpp.JID(vmjid), vmname, vmpass, start=False, organizationInfo=self.entity.vcard_infos)
            vm = vm_thread.get_instance()
            vm.register_hook("HOOK_ARCHIPELENTITY_XMPP_AUTHENTICATED", method=vm.define_hook, user_info=domain, oneshot=True)
            if vm_info["start"]:
                vm.register_hook("HOOK_ARCHIPELENTITY_XMPP_AUTHENTICATED", method=vm.control_create_hook, oneshot=True)
            vm_thread.start()
            self.set_vms_status([vm_info])

        self.entity.push_change("vmparking", "unparked")
        self.entity.log.info("VMPARKING: successfully unparked %s" % str(vmjid))
Example #18
0
    def start(self, gmail_account, password):
        jid = xmpp.JID(gmail_account)
        user, server, password = jid.getNode(), jid.getDomain(), password

        self.conn = xmpp.Client(server, debug=self.debug)
        #talk.google.com
        conres = self.conn.connect(server=(self.server_host, self.server_port))
        if not conres:
            print "Unable to connect to server %s!" % server
            sys.exit(1)
        if conres <> 'tls':
            print "Warning: unable to estabilish secure connection - TLS failed!"

        authres = self.conn.auth(user, password)
        if not authres:
            print "Unable to authorize on %s - Please check your name/password." % server
            sys.exit(1)
        if authres <> "sasl":
            print "Warning: unable to perform SASL auth os %s. Old authentication method used!" % server

        self.conn.RegisterHandler("message", self.controller)
        self.conn.RegisterHandler('presence', self.presenceHandler)

        self.conn.sendInitPresence()

        self.setState(self.show, self.status)

        print "Bot started."
        self.GoOn()
Example #19
0
    def delete(self, vm_uuids):
        """
        Delete a parked virtual machine
        @type vm_uuids: list
        @param uuid: list of dic like {"uuid": x}
        """
        vm_jids = []
        # first, check there is no problems
        for vm_uuid in vm_uuids:
            if not self.is_vm_parked(vm_uuid["uuid"]):
                raise Exception("There is no virtual machine parked with uuid %s" % vm_uuid["uuid"])
            vm_item = self.get_vm_by_uuid_from_db(vm_uuid["uuid"])
            vm_jids.append(xmpp.JID(vm_item["domain"].getTag("description").getData().split("::::")[0]))

        # Update DB and Push
        self.unregister_vms_from_db(vm_uuids)
        self.entity.push_change("vmparking", "deleted")

        # Then perfom cleanup operations
        for vm_jid in vm_jids:
            vmfolder = "%s/%s" % (self.configuration.get("VIRTUALMACHINE", "vm_base_path"), vm_jid.getNode())
            if os.path.exists(vmfolder):
                shutil.rmtree(vmfolder)

        # And remove the XMPP account
        self.entity.get_plugin("xmppserver").users_unregister(vm_jids)
        self.entity.log.info("VMPARKING: successfully deleted %s from parking" % str(vm_jids))
Example #20
0
    def __init__(self, username, password, res=None, debug=False):
        """Initializes the jabber bot and sets up commands."""
        self.__debug = debug
        self.log = logging.getLogger(__name__)
        self.__username = username
        self.__password = password
        self.jid = xmpp.JID(self.__username)
        self.res = (res or self.__class__.__name__)
        self.conn = None
        self.__finished = False
        self.__exitcode = 0
        self.__show = None
        self.__status = None
        self.__seen = {}
        self.__threads = {}

        self.commands = {}
        for name, value in inspect.getmembers(self):
            if inspect.ismethod(value) and getattr(value, '_jabberbot_command', False):
                name = getattr(value, '_jabberbot_command_name')
                if self.__debug:
                    self.log.debug('Registered command: %s' % name)
                self.commands[name] = value

        self.roster = None
Example #21
0
def is_registered(jid, spool=conf.profile_dir):
    bare_jid = xmpp.JID(jid).getStripped()
    file = os.path.join(spool, bare_jid + '.xdb')
    if os.path.exists(file) and os.path.isfile(file):
        return True
    else:
        return False
Example #22
0
    def send(self, mess):
        """send a message to the specified recipient"""

        (text, to) = (mess.get_text(), mess.get_to())

        if mess.get_emote():
            text = '/me ' + mess.get_text()

        mess = self.__build_message(text)
        mess.setType('chat')
        if isinstance(to, Room):
            mess.setType('groupchat')
            to = to.get_name()
        mess.setTo(xmpp.JID(str(to)))

        # outer try block catches disconnected from _sock.recv() and conn.send()
        try:

            # check if the socket is dead (send doesn't do that, so we'll recv)
            # if recv() raises an exception it timed out and everything is fine
            # if it returns an empty string the socket is dead
            try:
                if not self.conn.Connection._sock.recv(1, socket.MSG_PEEK):
                    raise IOError
            except socket.error as e:
                pass

            # actually try to send the message
            self.conn.send(mess)

        except IOError:
            self.disconnected(self.ConnectFailure)
Example #23
0
    def connect(self):
        self.disconnected = False
        jid = xmpp.JID(self.login)
        user, server, password = jid.getNode(), jid.getDomain(), self.password
        self.conn = xmpp.Client(server, debug=[])
        conres = self.conn.connect(server=(self.server_host, self.server_port))
        if not conres:
            print "Unable to connect to server %s!" % server
            sys.exit(1)
        if conres <> 'tls':
            print "Warning: unable to estabilish secure connection - TLS failed!"

        authres = self.conn.auth(user, password, "laptop")
        if not authres:
            print "Unable to authorize on %s - Plsese check your name/password." % server
            sys.exit(1)
        if authres <> "sasl":
            print "Warning: unable to perform SASL auth os %s. Old authentication method used!" % server

        self.conn.RegisterHandler("message", self.controller)
        self.conn.RegisterHandler('presence', self.presenceHandler)
        self.conn.RegisterDisconnectHandler(self.on_disconnect)
        self.conn.sendInitPresence()
        self.setState(self.show, self.status)
        if self.timer:
            try:
                self.timer.cancel()
            except:
                pass
        self.timer = threading.Timer(600, self.ping)
        self.timer.start()
Example #24
0
def messageCB(con, msg):
	msgtype = msg.getType()
	body = msg.getBody()
	if body != None:
		body = body.strip()
	fromjid = msg.getFrom()
	command = ''
	parameters = ''
	if body and string.split(body):
		command = string.lower(string.split(body)[0])
		if body.count(' '):
			parameters = body[(body.find(' ') + 1):]
	if not msg.timestamp:
		if msgtype == 'groupchat':
				call_message_handlers('public', [fromjid, fromjid.getStripped(), fromjid.getResource()], body)
				if command in COMMANDS:
					call_command_handlers(command, 'public', [fromjid, fromjid.getStripped(), fromjid.getResource()], parameters)
		else:
			call_message_handlers('private', [fromjid, fromjid.getStripped(), fromjid.getResource()], body)
			if command in COMMANDS:
				call_command_handlers(command, 'private', [fromjid, fromjid.getStripped(), fromjid.getResource()], parameters)
	for x_node in msg.getTags('x', {}, 'jabber:x:conference'):
		inviter_jid = None
		muc_inviter_tag = msg.getTag('x', {}, 'http://jabber.org/protocol/muc#user')
		if muc_inviter_tag:
			if muc_inviter_tag.getTag('invite'):
				if muc_inviter_tag.getTag('invite').getAttr('from'):
					inviter_jid = xmpp.JID(muc_inviter_tag.getTag('invite').getAttr('from'))
		if not inviter_jid:
			inviter_jid = fromjid
		call_groupchat_invite_handlers([inviter_jid, inviter_jid.getStripped(), inviter_jid.getResource()], x_node.getAttr('jid'), body)
Example #25
0
def command_remember(bot, room, nick, access_level, parameters, message):
  try: (term, definition) = parameters.split(' ', 1)
  except: return "Expected: <term> <definition>"

  jid = bot.roster[room][nick][ROSTER_JID]
  if jid != None: jid = xmpp.JID(jid).getStripped().lower()

  for c in term: 
    if ord(c) > 127 or ord(c)<32:
      return "Bad term, don't use unicode."

  if term == '' or term == ':':
    return "The term is empty."

  # remove : added by common mistake
  if term[-1] == ':': term = term[:-1]
  
  term_key = term.lower()

  existent_term = getterm(bot, room, term_key)
  if existent_term and access_level < LEVEL_ADMIN:
    if existent_term['jid'] != jid:
      return "You can't redefine %s."%(term)
    
  if access_level < LEVEL_ADMIN:
    definition +=' (added by '+nick+')'
  termdic = {
    'def': definition,
    'jid': jid,
    'time': time.time(),
  }
  setterm(bot, room, term_key, termdic)
  return "I know %s!"%(term)
Example #26
0
        def _unpark_callback(vm_items):

            vm_information_by_uuid  = {}

            for vm_info in vm_information:
                vm_information_by_uuid[vm_info["uuid"]] = vm_info

            for vm_item in vm_items:
                vm_info = vm_information_by_uuid[vm_item["uuid"]]
                domain = vm_item["domain"]
                ret = str(domain).replace('xmlns=\"archipel:hypervisor:vmparking\"', '')
                domain = xmpp.simplexml.NodeBuilder(data=ret).getDom()
                vmjid = domain.getTag("description").getData().split("::::")[0]
                vmpass = domain.getTag("description").getData().split("::::")[1]
                vmname = domain.getTag("name").getData()
                self.entity.log.debug("VMPARKING: about to create vm thread")
                vm_thread = self.entity.soft_alloc(xmpp.JID(vmjid), vmname, vmpass, start=False, organization_info=self.entity.vcard_infos)
                vm = vm_thread.get_instance()
                vm.register_hook("HOOK_ARCHIPELENTITY_XMPP_AUTHENTICATED", method=vm.define_hook, user_info=domain, oneshot=True)
                if vm_info["start"]:
                    vm.register_hook("HOOK_ARCHIPELENTITY_XMPP_AUTHENTICATED", method=vm.control_create_hook, oneshot=True)
                vm_thread.start()
    
                self.entity.push_change("vmparking", "unparked")
                self.entity.log.info("VMPARKING: successfully unparked %s" % str(vmjid))
Example #27
0
 def __init__(self):
     try:
         with open(secrets_filename, "r") as f:
             data = f.read()
     except:
         err = "Error processing {} - make sure to fill in {} and reading the " + \
          "instructions in discover_gchat_id.py".format(secrets_filename, secrets_filename)
         with open(secrets_filename, "w") as f:
             f.write(document)
         raise Exception(err)
     try:
         conf = yaml.load(data)
         self.automation_user = conf["automation_user"]
         self.automation_password = conf["automation_password"]
         self.automation_server = conf["automation_server"]
         self.automation_port = conf["automation_port"]
         self.destination_user = conf["destination_user"]
     except:
         raise Exception("Error parsing {}!".format(secrets_filename))
     if self.automation_user is None or self.automation_password is None or self.automation_server is None or \
      self.automation_port is None or self.destination_user is None:
         raise Exception(
             "Error parsing {} - not all fields have been filled in!".
             format(secrets_filename))
     server = (self.automation_server, self.automation_port)
     jid = xmpp.JID(self.automation_user)
     self.connection = xmpp.Client(jid.getDomain(), debug=[])
     self.connection.connect(server)
     result = self.connection.auth(jid.getNode(), self.automation_password)
     self.connection.sendInitPresence()
Example #28
0
 def retract_success(resp, user_info):
     if resp.getType() == "result":
         domain = vm_item.getTag("virtualmachine").getTag("domain")
         ret = str(domain).replace(
             'xmlns=\"archipel:hypervisor:vmparking\"', '')
         domain = xmpp.simplexml.NodeBuilder(data=ret).getDom()
         vmjid = domain.getTag("description").getData().split("::::")[0]
         vmpass = domain.getTag("description").getData().split(
             "::::")[1]
         vmname = domain.getTag("name").getData()
         vm_thread = self.entity.soft_alloc(xmpp.JID(vmjid),
                                            vmname,
                                            vmpass,
                                            start=False)
         vm = vm_thread.get_instance()
         vm.register_hook("HOOK_ARCHIPELENTITY_XMPP_AUTHENTICATED",
                          method=vm.define_hook,
                          user_info=domain,
                          oneshot=True)
         if start:
             vm.register_hook("HOOK_ARCHIPELENTITY_XMPP_AUTHENTICATED",
                              method=vm.control_create_hook,
                              oneshot=True)
         vm_thread.start()
         self.inhibit_next_general_push = True
         self.entity.push_change("vmparking", "unparked")
         self.entity.log.info("VMPARKING: successfully unparked %s" %
                              str(vmjid))
     else:
         self.inhibit_next_general_push = True
         self.entity.push_change("vmparking",
                                 "cannot-unpark",
                                 content_node=resp)
         self.entity.log.error("VMPARKING: cannot unpark: %s" %
                               str(resp))
Example #29
0
    def create_parked(self, uuid, xmldesc, parker_jid, push=True):
        """
        Creates a VM directly into the parking.
        @type uuid: String
        @param uuid: The UUID of the VM to create and park
        @type xmldesc: xmpp.simplexml.Node
        @param xmldesc: The XML desc to park. The UUID inside must the same than UUID parameter
        @type parker_jid: xmpp.protocol.JID
        @param parker_jid: the JID of the parker
        """
        if self.is_vm_already_parked(uuid):
            raise Exception("VM with UUID %s is already parked" % uuid)

        vm = self.entity.get_vm_by_uuid(uuid)
        if vm:
            raise Exception("There is already a VM with UUID %s" % uuid)

        if xmldesc.getTag("description"):
            raise Exception(
                "You cannot park a VM XML with a <description/> tag. Please remove it"
            )
        password = ''.join(
            [random.choice(string.letters + string.digits) for i in range(32)])
        xmldesc.addChild("description").setData(
            "%s@%s::::%s" % (uuid, self.entity.jid.getDomain(), password))

        vm_jid = xmpp.JID(
            xmldesc.getTag("description").getData().split("::::")[0])

        self.add_vm_into_db(uuid, parker_jid, xmldesc)
        self.entity.log.info(
            "VMPARKING: New virtual machine %s as been parked" % uuid)
        if push:
            self.entity.push_change("vmparking", "parked")
class CollaborativeMicroblogging:
    def message_handler(connect_object, message_node):
        command1 = str(unicode(message_node.getBody()).encode('utf-8'))
        command2 = str(message_node.getFrom().getStripped())
        c3 = command2.replace("@", " [at] ")
        c4 = c3.replace(".", " [dot] ")
        auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
        api = tweepy.API(auth)
        api.update_status(command1)

        connect_object.send(
            xmpp.Message(message_node.getFrom(),
                         ("Posted your message on Twitter " + command1)))

    jid = xmpp.JID(user)
    connection = xmpp.Client(server)
    connection.connect()
    result = connection.auth(jid.getNode(), passwd)
    connection.RegisterHandler('message', message_handler, "")
    connection.sendInitPresence()
    press = xmpp.Presence()
    press.setStatus("Hi from Collaborative Microblogging App")
    connection.send(press)

    while (1):
        connection.Process(1)