Exemplo n.º 1
0
 def __init__(self, module, pref):
     self.module = str(module)
     self.name = str(pref)
     if self.module in xa.gModules:
         if not self.module in gKeyValues:
             gKeyValues[self.module] = keyvalues.KeyValues(name=self.module)
         if not self.name in gKeyValues[self.module]:
             gKeyValues[self.module][self.name] = keyvalues.KeyValues(
                 name=self.name)
Exemplo n.º 2
0
 def createKey(self, name):
     if self.filetype == 'keyvalues':
         return keyvalues.KeyValues(name=name)
     elif self.filetype == 'dict':
         return {}
     else:
         return None
Exemplo n.º 3
0
def player_say(event_var):
    # probably the best way
    if event_var['text'] == "!menu":
        dlg = msglib.VguiDialog(title="menu1",
                                msg="themessage",
                                mode=msglib.VguiMode.MENU)
        dlg["msg"] = "This is a long message.\nYes it is! Never forget me!\n\n\nNo!\n"
        dlg.addOption(msg="Hello", command="echo Hello")
        dlg.addOption(msg="Hello1", command="echo Hello1")
        dlg.addOption(msg="Hello2", command="echo Hello2")
        dlg.addOption(msg="Hello3", command="echo Hello3")
        dlg.addOption(msg="Hello4", command="echo Hello4")
        dlg = msglib.VguiDialog(title="My Title",
                                msg="My Message",
                                mode=msglib.VguiMode.TEXT)
        dlg.send(event_var['userid'])

    # keyvalue way if you want
    if event_var['text'] == "!go":
        kv = keyvalues.KeyValues(name="message")
        kv["msg"] = "THIS IS THE MESSAGE"
        kv["title"] = "TITLE!"
        kv["level"] = 5
        kv["color"] = "255 255 0 255"
        kv["time"] = 20
        for x in kv:
            print x.getName(), kv[x.getName()]
        msglib.sendVguiDialog(event_var['userid'], msglib.VguiType.TEXT, kv)
Exemplo n.º 4
0
def getKeyList(module, filename, modfolder = False):
    if modfolder == False:
        filename = ("%s/cfg/xa/%s" % (xa.gamedir(), filename)).replace("\\", "/")
    else:
        filename = ("%s/%s" % (xa.gamedir(), filename)).replace("\\", "/")
    if os.path.exists(filename):
        kv = keyvalues.KeyValues()
        kv.load(filename)
        return kv
    return False
Exemplo n.º 5
0
 def __init__(self,
              title="Dialog",
              msg="Dialog",
              level=5,
              color="255 255 255 255",
              time=10,
              mode=VguiMode.MSG):
     self.kv = keyvalues.KeyValues(name=title)
     self.kv['title'] = title
     self.kv['msg'] = msg
     self.kv['level'] = level
     self.kv['color'] = color
     self.kv['time'] = time
     self.mode = mode
     self.nextoption = 1
Exemplo n.º 6
0
def getKeyList(module, filename, modfolder = False):
    # Is the filename relative to the modfolder?
    if modfolder:
        filename = ('%s/%s' % (xa.gamedir(), filename)).replace('\\', '/')
    else:
        filename = ('%s/cfg/xa/%s' % (xa.gamedir(), filename)).replace('\\', '/')
    
    # Does the file exist?
    if os.path.exists(filename):
        # Load the file into a new KeyValues object
        try:
            kv = keyvalues.KeyValues()
            kv.load(filename)
        except:
            kv = None
        
        # Return ou new KeyValues object
        return kv
Exemplo n.º 7
0
def convertOldDatabase():
    """
        Converts old style keyvalue based databases (pre 1.1) to 1.1 style dict based database
    """
    import keyvalues
    oldPlayerSettings = keyvalues.KeyValues(name='playerdata.txt')
    oldPlayerSettings.load('%s/data/playerdata.txt' % es.getAddonPath('xa'))
    for moduleKeyValue in oldPlayerSettings:
        module = str(moduleKeyValue)
        gPlayerData[module] = {}
        for settingKeyValue in moduleKeyValue:
            setting = str(settingKeyValue)
            gPlayerData[module][setting] = {}
            for steamidKeyValue in settingKeyValue:
                steamid = str(steamidKeyValue)
                try:
                    gPlayerData[module][setting][steamid] = oldPlayerSettings[module][setting][steamid]
                except:
                    es.dbgmsg(0, "xa: playerdata - Error converting module %s, setting %s and steamid %s" % (module, setting, steamid) )
    saveUserSetting()
Exemplo n.º 8
0
def keyfilter_cmd(args):
    if len(args) > 3:
        keygroup = args[0]
        if es.exists('keygroup', keygroup):
            key = args[1]
            if es.exists('key', keygroup, key):
                action = args[2]
                if action in ['not', 'only']:
                    kv = keyvalues.getKeyGroup(keygroup)
                    keyfiltervar = args[3]
                    keyfilterlist = []
                    if len(args) > 4:
                        keyfiltervalue = args[4]
                    else:
                        keyfiltervalue = None
                    if action == 'not':
                        for keyvar in kv[key].keys():
                            if keyfiltervar in keyvar and (str(kv[key][keyvar]) == keyfiltervalue or not keyfiltervalue):
                                keyfilterlist.append(keyvar)
                    elif action == 'only':
                        for keyvar in kv[key].keys():
                            if not keyfiltervar in keyvar or (str(kv[key][keyvar]) != keyfiltervalue and keyfiltervalue):
                                keyfilterlist.append(keyvar)
                    for keyvar in keyfilterlist:
                        if keyvar in kv[key]:
                            kv[key][keyvar] = keyvalues.KeyValues(name=' ')
                    if keyfilterlist:
                        # Let's remove our deleted keys by reloading the keygroup with classic ES commands 
                        es.keygroupsave(keygroup, '|corelib/keyfilter')
                        es.keygroupdelete(keygroup)
                        es.keygroupcreate(keygroup)
                        es.keygroupload(keygroup, '|corelib/keyfilter')
                        os.unlink(es.getAddonPath('corelib/keyfilter')+'/es_%s_db.txt'%keygroup)
                else:
                    es.dbgmsg(0, 'keyfilter: Invalid action provided. Syntax: keyfilter <keygroup> <key> <not/only> <part-of-value-name> [value]')
            else:
                es.dbgmsg(0, 'keyfilter: Invalid key for keygroup "%s" provided: %s' % (keygroup, key))
        else:
            es.dbgmsg(0, 'keyfilter: Invalid keygroup provided: %s' % keygroup)
    else:
        es.dbgmsg(0, 'keyfilter: Not enough arguments to keyfilter. Syntax: <keygroup> <key> <not/only> <part-of-value-name> [value]')
Exemplo n.º 9
0
import es
import playerlib
import keyvalues
import xa

import psyco

psyco.full()

gSettingFile = "%s/data/playerdata.txt" % es.getAddonPath('xa')
gKeyValues = keyvalues.KeyValues(name="playerdata.txt")
gKeyValues.load(gSettingFile)


###########################
#Module methods start here#
########################################################
# All methods that should be able to be called through #
# the API need to have "module" as first parameter     #
########################################################
class UserSetting(object):
    def __init__(self, module, pref):
        self.module = str(module)
        self.name = str(pref)
        if self.module in xa.gModules:
            if not self.module in gKeyValues:
                gKeyValues[self.module] = keyvalues.KeyValues(name=self.module)
            if not self.name in gKeyValues[self.module]:
                gKeyValues[self.module][self.name] = keyvalues.KeyValues(
                    name=self.name)
Exemplo n.º 10
0
    def refreshClients(self):
        # Get client list
        path = self._convertClientsFile(self.clientspath)
        clientdata = keyvalues.KeyValues('clients.txt')
        clientdata.load(path)
        os.remove(path)

        if 'players' not in clientdata:
            raise KeyError, 'clients.txt has no "players" section'
        self.clients.clear()

        # Parse the client data
        clientplayers = clientdata['players']
        for player in clientplayers:
            steamid = []
            flags = []
            for attr in player:
                attr_name = attr.getName()
                # Snag SteamIDs for this player
                if attr_name == 'steam':
                    player_steam = attr.getString()
                    if player_steam:
                        steamid += [player_steam]
                    else:
                        steamid += [x.getString() for x in attr]

                # Add the flags of groups this player belongs to
                elif attr_name in clientdata:
                    group = clientdata[attr_name]
                    player_group = attr.getString()
                    if player_group:
                        player_group = (attr, )
                    else:
                        player_group = attr
                    for x in player_group:
                        group_name = x.getString() if isinstance(
                            player_group, tuple) else x.getName()
                        for y in group:
                            if y.getName() == group_name:
                                flag_string = y.getString()
                                if flag_string:
                                    flags += y.getString().split()
                                else:
                                    for z in y:
                                        if z.getName() == x.getString():
                                            flags += z.getString().split()

                # Add individual flags
                elif attr_name == 'flags':
                    player_flags = attr.getString()
                    if not player_flags:
                        player_flags = ' '.join([x.getString() for x in attr])
                    flags += player_flags.split()

            # Put player in clients dictionary with respective flags
            if steamid and flags:
                # Making the flag list a set ensures each flag is only present once
                flagset = set(flags)
                # All flags are registered to capabilities at the ROOT level so admins aren't authed for flags they don't have
                for f in flagset:
                    self.registerCapability('mani_flag_' + f, self.ROOT)
                for s in steamid:
                    self.clients[s] = flagset
Exemplo n.º 11
0
   def _importManiClients(self, args):
      # No clients, nothing to import
      if not os.path.isfile(self.clients_path):
         raise IOError, 'ini_tree_auth: Cannot find ./cfg/mani_admin_plugin/clients.txt to import Mani clients'

      """ Gather the contents of Mani's clients.txt"""
      # Remove Unicode characters from clients.txt
      nf = open(self.auth_path + 'clients.txt', 'wb')
      of = open(self.clients_path, 'rb')
      nf.write(filter(lambda x: ord(x) <= 127, of.read()))
      of.close()
      nf.close()

      # Load the new clients.txt and then remove it
      clientdata = keyvalues.KeyValues('clients.txt')
      clientdata.load(self.auth_path + 'clients.txt')
      os.remove(self.auth_path + 'clients.txt')

      if 'players' not in clientdata:
         raise KeyError, 'clients.txt has no "players" section'

      # Parse the client data
      clientplayers = clientdata['players']
      for player in clientplayers:
         steamid = []
         flags   = []
         for attr in player:
            attr_name = attr.getName()
            # Snag SteamIDs for this player
            if attr_name == 'steam':
               player_steam = attr.getString()
               if player_steam:
                  steamid += [player_steam]
               else:
                  steamid += [x.getString() for x in attr]

            # Add the flags of groups this player belongs to
            elif attr_name in clientdata:
               group = clientdata[attr_name]
               player_group = attr.getString()
               if player_group:
                  player_group = (attr,)
               else:
                  player_group = attr
               for x in player_group:
                  group_name = x.getString() if isinstance(player_group, tuple) else x.getName()
                  for y in group:
                     if y.getName() == group_name:
                        flag_string = y.getString()
                        if flag_string:
                           flags += y.getString().split()
                        else:
                           for z in y:
                              if z.getName() == x.getString():
                                 flags += z.getString().split()

            # Add individual flags
            elif attr_name == 'flags':
               player_flags = attr.getString()
               if not player_flags:
                  player_flags = ' '.join([x.getString() for x in attr])
               flags += player_flags.split()

         # Put player in clients dictionary with respective flags
         if steamid and flags:
            # Making the flag list a set ensures each flag is only present once
            flagset = set(flags)
            # All flags are registered to capabilities at the ROOT level so admins aren't authed for flags they don't have
            for f in flagset:
               ini_tree_auth.registerCapability('mani_flag_' + f, self.ROOT)
            for s in steamid:
               group = 'ADMIN' if 'admin' in flagset else 'POWERUSER'
               for f in flagset:
                  if s not in self.ini_file[group]:
                     self.ini_file[group][s] = {}
                  self.ini_file[group][s]['mani_flag_' + f] = 'True'

      # Write the newly imported clients to the ini
      self.ini_file.write()
Exemplo n.º 12
0
    def get_item_data(self):
        #get the latest item schema from the steam API

        weapon_dict = self.get_default_weapons()

        if not self.__item_data_url:
            logging.info("Don't have item_games.txt URL, using static weapons")
            return weapon_dict

        logging.info("Getting item data")

        try:
            items_game_res = urllib2.urlopen(self.__item_data_url)
        except:
            logging.exception("Unable to load items_game.txt")
            return

        # parse the items_game.txt keyvalues formatted file into a
        # python dictionary
        kv_parser = keyvalues.KeyValues()

        items_game_data = kv_parser.parse(items_game_res.read())

        items_game_res.close()
        del items_game_res  #free memory

        if not items_game_data:
            logging.info(
                "Unable to get item data. Using only static weapon data")
            return weapon_dict

        logging.info(
            "Item data received. Populating weapon dict with non-static weapons"
        )

        if "items" in items_game_data["items_game"]:
            #we have all items in a dictionary! now let's loop over them
            item_dict = items_game_data["items_game"]["items"]
            for item_key in item_dict:
                item = item_dict[item_key]

                if "used_by_classes" in item and "item_logname" in item:
                    item_classes = item["used_by_classes"]
                    for pclass_u in item_classes:
                        #now we have individual classes per item
                        pclass = pclass_u.encode(
                            'ascii', 'ignore'
                        )  #convert the class name to plain ASCII instead of unicode
                        if pclass not in weapon_dict:
                            weapon_dict[pclass] = [
                                item["item_logname"].encode('ascii', 'ignore')
                            ]  #convert item name to ASCII before adding
                        else:
                            weapon_dict[pclass].append(
                                item["item_logname"].encode('ascii', 'ignore')
                            )  #convert item name to ASCII before adding

        #move "heavy" to "heavyweapons", because the game uses the latter rather than the former
        weapon_dict["heavyweapons"] += weapon_dict["heavy"]
        del weapon_dict["heavy"]  #remove old key

        logging.info("Weapon dict populated with non-static weapons")

        items_game_data = None

        return weapon_dict
Exemplo n.º 13
0
 def addOption(self, msg="Option", command="echo 1"):
     names = str(self.nextoption)
     self.kv[names] = keyvalues.KeyValues(name=names)
     self.kv[names]["msg"] = msg
     self.kv[names]["command"] = command
     self.nextoption = self.nextoption + 1
Exemplo n.º 14
0
)
quake_sounds_soundload = es.ServerVar(
    'quake_sounds_soundload', '1',
    'Should the sounds be downloaded with EventScripts?')
quake_sounds_multikill_time = es.ServerVar(
    'quake_sounds_multikill_time', '1.5',
    'The time between kills that counts up the multikill count? ( >0 )')

# Global Variables
quake_sounds_language = langlib.Strings(
    es.getAddonPath('quake_sounds') + '/language.ini')
quake_sounds_kills = 0
quake_sounds_players = {}

# KeyValues Object
quake_sounds_kv = keyvalues.KeyValues(name='quake_sounds')

# Settinglib Object
quake_sounds_setting = settinglib.create('quakesounds', 'Quake Sounds Style',
                                         'list')

# Module Object
quake_sounds_module = __import__('quake_sounds.quake_sounds')


def load():
    public = es.ServerVar('hu_qs', info.version, info.name)
    public.makepublic()

    quake_sounds_players = {}
    for userid in es.getUseridList():
Exemplo n.º 15
0
def run_conversion():
    # List the file names from ../cfg/gungame51/converter/
    for file_path in convertDir.files():

        file_name = file_path.name

        # If the file is the README.txt or an already converted file, skip it
        if file_name == 'README.txt' or file_name[-10:] == '.converted':
            continue

        # --------------------------------------------------------------------
        # GunGame3 Winners Conversion
        # --------------------------------------------------------------------
        if file_name == 'es_gg_winners_db.txt':
            # If gg_convert is set to 2, delete the winners database
            check_delete()

            # Create a new KeyValues instance
            kv = keyvalues.KeyValues(name='gg3_winners')
            # Load the winners database into the KeyValues instance
            kv.load(file_path)

            # For every uniqueid that we will be converting
            for uniqueid in kv:
                uniqueid = str(uniqueid)

                # If it is not a proper uniqueid, skip it
                if not uniqueid.startswith('STEAM_'):
                    continue

                # Add the winner to the current database
                add_winner(kv[uniqueid]['name'], uniqueid,
                           kv[uniqueid]['wins'], int(time.time()))

        # --------------------------------------------------------------------
        # GunGame4 Winners Conversion
        # --------------------------------------------------------------------
        elif file_name == 'es_gg_database.sqldb':
            # If gg_convert is set to 2, delete the winners database
            check_delete()

            # Connect to the sqldb file
            sqldb = connect(file_path)
            # Create the cursor
            cursor = sqldb.cursor()
            # Prepare the query
            cursor.execute('select * from gg_players')
            # Store the output in a list
            gg_players = cursor.fetchall()
            # Close the connection
            sqldb.close()

            # For every player in the database
            for player in gg_players:
                # Get their wins
                wins = player[2]

                # If the player has on wins, skip them
                if not wins:
                    continue

                # Add the winner to the current database
                add_winner(player[0], player[1], wins, player[-1])

        # --------------------------------------------------------------------
        # GunGame5 Winners Conversion
        # --------------------------------------------------------------------
        elif file_name == 'winnersdata.db':
            # If gg_convert is set to 2, delete the winners database
            check_delete()

            # Load the cPickle'd database into the winners dictionary
            with file_path.open() as winnersDataBaseFile:
                winners = cPickle.load(winnersDataBaseFile)

            # For every uniqueid in the winners database
            for uniqueid in winners:
                # Add the winner to the current database
                add_winner(winners[uniqueid]['name'], uniqueid,
                           winners[uniqueid]['wins'],
                           int(winners[uniqueid]['timestamp']))

        # --------------------------------------------------------------------
        # GunGame3 SpawnPoints Conversion
        # --------------------------------------------------------------------
        elif file_name[-7:] == '_db.txt':
            # Create a new KeyValues instance
            kv = keyvalues.KeyValues(name=file_name[3:-7])
            # Load the spawnpoints database into the KeyValues instance
            kv.load(file_path)

            convertedSpawnPoints = []

            # For every spawnpoint in the database, put them in our list
            for point in kv['points']:
                convertedSpawnPoints.append(
                    kv['points'][str(point)].replace(',', ' ') +
                    ' 0.000000 0.000000 0.000000\n')

            # Write the spawnpoints to the spawnpoint file
            write_spawnpoint_file(file_name, file_name[3:-7],
                                  convertedSpawnPoints)

        # --------------------------------------------------------------------
        # GunGame4 Spawnpoints Conversion
        # --------------------------------------------------------------------
        elif file_name[-6:] == '.sqldb':
            # Connect to the sqldb file
            sqldb = connect(file_path)
            # Create the cursor
            cursor = sqldb.cursor()
            # Prepare the query
            cursor.execute('select * from spawnpoints')
            # Store the output in a list
            spawnPoints = cursor.fetchall()
            # Close the connection
            sqldb.close()

            convertedSpawnPoints = []

            # For every spawnpoint in the database, put them in our list
            for point in spawnPoints:

                # If the spawnpoint is not valid, skip it
                if float(x) == 0 and float(y) == 0 and float(z) == 0:
                    continue

                convertedSpawnPoints.append('%s %s %s %s %s 0.000000\n' %
                                            tuple(point[2:7]))

            # Write the spawnpoints to the spawnpoint file
            write_spawnpoint_file(file_name, file_name[3:-6],
                                  convertedSpawnPoints)

        # Store the name which the completed file will be renamed to
        renameTo = file_path + '.converted'

        # Prepare to differentiate the file with a number if it already exists
        x = 1

        # As long as the file already exists
        while renameTo.isfile():

            # Differentiate the file by putting a number in it
            renameTo = (file_path + '[' + str(x) + ']' + '.converted')

            # Increment the number
            x += 1

        # Rename the file
        file_path.rename(renameTo)

    # Commit the queries to the database
    ggDB.commit()