Beispiel #1
0
def update_data(timeout=3):
    """Download and unpack the latest data from the build server.

    :param float timeout:
        Number of seconds that need to pass until a timeout occurs.
    """
    download_latest_data(timeout)
    if SP_DATA_PATH.isdir():
        update_logger.log_debug('Removing {} ...'.format(SP_DATA_PATH))
        SP_DATA_PATH.rmtree()

    unpack_data()
def update_data(timeout=DEFAULT_TIMEOUT):
    """Download and unpack the latest data from the build server.

    Old data gets deleted before unpacking.

    :param float timeout:
        Number of seconds that need to pass until a timeout occurs.
    """
    _download_latest_data(timeout)
    if SP_DATA_PATH.isdir():
        update_logger.log_debug('Removing {} ...'.format(SP_DATA_PATH))
        SP_DATA_PATH.rmtree()

    _unpack_data()
Beispiel #3
0
def update_data(timeout=DEFAULT_TIMEOUT):
    """Download and unpack the latest data from the build server.

    Old data gets deleted before unpacking.

    :param float timeout:
        Number of seconds that need to pass until a timeout occurs.
    """
    _download_latest_data(timeout)
    if SP_DATA_PATH.isdir():
        update_logger.log_debug('Removing {} ...'.format(SP_DATA_PATH))
        SP_DATA_PATH.rmtree()

    _unpack_data(DATA_PATH)
Beispiel #4
0
    def print_credits(self):
        """List all credits for Source.Python."""
        # Get header messages
        message = self.prefix + _plugin_strings[
            'Credits'].get_string() + '\n' + '=' * 61 + '\n\n'

        # Get the credits information
        groups = ConfigObj(
            SP_DATA_PATH.joinpath('credits.ini'), encoding='unicode_escape')

        # Loop through all groups in the credits
        for group in groups:

            # Add the current group's name
            message += '\t' + group + ':\n'

            # Loop through all names in the current group
            for name in groups[group]:

                # Add the current name
                message += '\t\t' + name + ' ' * (
                    20 - len(name)) + groups[group][name] + '\n'

            # Add 1 blank line between groups
            message += '\n'

        # Print the message
        self.logger.log_message(message + '=' * 61 + '\n\n')
Beispiel #5
0
def _print_credits():
    '''Lists all credits for Source.Python.'''

    # Get header messages
    message = '[SP] ' + _command_strings[
        'Credits'].get_string() + '\n' + '=' * 61 + '\n\n'

    # Get the credits information
    groups = ConfigObj(
        SP_DATA_PATH.joinpath('credits.ini'), encoding='unicode_escape')

    # Loop through all groups in the credits
    for group in groups:

        # Add the current group's name
        message += '\t' + group + ':\n'

        # Loop through all names in the current group
        for name in groups[group]:

            # Add the current name
            message += '\t\t' + name + ' ' * (
                20 - len(name)) + groups[group][name] + '\n'

        # Add 1 blank line between groups
        message += '\n'

    # Print the message
    _CoreCommandsLogger.log_message(message + '=' * 61 + '\n\n')
Beispiel #6
0
    def _retrieve_attributes(self, entity):
        '''Retrieves all attributes for the given entity'''

        # Create an empty dictionary
        game_attributes = dict()

        # Get the path to the entity's attributes
        inifile = SP_DATA_PATH.joinpath(self.type, entity, GAME_NAME + '.ini')

        # Does the file exist?
        if not inifile.isfile():

            # Return the empty dictionary
            return game_attributes

        # Get the file's contents
        ini = ConfigObj(inifile, unrepr=self.unrepr)

        # Loop through all items in the file
        for key in ini:

            # Use try/except in case an error occurs
            try:

                # Get the object for the current key
                value = self.instance(ini[key])

            # Was an error encountered?
            except:

                # Get the exception
                exctype, value, trace_back = sys.exc_info()

                # Log the error as a warning
                EntitiesAttributesLogger.log_warning(
                    'Unable to add attribute "{0}"'.format(key) +
                    'of type "{0}" to entity type '.format(self.type) +
                    '"{0}" due to the following:'.format(entity) +
                    '\n\t{0}'.format(value))

            # Was no error encountered?
            else:

                # Add the item to the dictionary
                game_attributes[key] = value

        # Return the dictionary
        return game_attributes
Beispiel #7
0
from core import GAME_NAME
from paths import SP_DATA_PATH


# =============================================================================
# >> ALL DECLARATION
# =============================================================================
# Set all to an empty list
__all__ = []


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Store the base "properties" path
_basepath = SP_DATA_PATH.joinpath('properties')


# =============================================================================
# >> CLASSES
# =============================================================================
class _Properties(dict):
    '''Dictionary that stores all entities with their properties'''

    def __missing__(self, item):
        '''Called the first time an entity is added to the dictionary'''

        # Get all properties for the given entity
        value = self[item] = _get_all_entity_properties(item)

        # Return the properties
Beispiel #8
0
from core import GAME_NAME
from paths import SP_DATA_PATH


# =============================================================================
# >> ALL DECLARATION
# =============================================================================
# Set all to an empty list
__all__ = []


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Store the base "offsets" path
_basepath = SP_DATA_PATH.joinpath('offsets')


# =============================================================================
# >> CLASSES
# =============================================================================
class _Offsets(dict):
    '''Dictionary that stores all entities with their offsets'''

    def __missing__(self, item):
        '''Called the first time an entity is added to the dictionary'''

        # Get all offsets for the given entity
        value = self[item] = _get_all_entity_offsets(item)

        # Return the offsets
Beispiel #9
0
# =============================================================================
# >> ALL DECLARATION
# =============================================================================
# Add all the global variables to __all__
__all__ = [
    'PlayerIter',
]


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get the team's file for the current game
_game_teams = ConfigObj(
    SP_DATA_PATH.joinpath('teams', GAME_NAME + '.ini'))


# =============================================================================
# >> MAIN PLAYER ITER CLASSES
# =============================================================================
class _PlayerIterManager(_BaseFilterManager):
    '''Filter management class specifically for player iterating'''

# Get the _PlayerIterManager instance
_PlayerIterManagerInstance = _PlayerIterManager()


class PlayerIter(_IterObject):
    '''Player iterate class'''
Beispiel #10
0
from configobj import ConfigObj

# Source.Python Imports
from core import GAME_NAME
from cvars import ServerVar
from paths import SP_DATA_PATH
from public import public
#   Weapons
from weapons.default import NoWeaponManager


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get the game's ini path
_gamepath = SP_DATA_PATH.joinpath('weapons', GAME_NAME + '.ini')


# =============================================================================
# >> CLASSES
# =============================================================================
@public
class _WeaponManager(dict):
    '''Dictionary class to store basic weapon information'''

    def __init__(self, ini_file):
        '''Loads the ini file into the dictionary'''

        # Get the ConfigObj instance of the file
        ini = ConfigObj(ini_file, unrepr=True)
Beispiel #11
0
class SQLBackend(Backend):
    """A backend that provides players and parents from an SQL database."""

    name = 'sql'
    options = {'uri': 'sqlite:///' + SP_DATA_PATH.joinpath('permissions.db')}

    def __init__(self):
        self.engine = None
        self.thread = None

    def load(self):
        self.engine = create_engine(self.options['uri'])
        Base.metadata.create_all(self.engine)
        Session.configure(bind=self.engine)
        self.start_sync()

    def unload(self):
        self.stop_sync()

    def sync(self):
        self.stop_sync()
        self.start_sync()

    def start_sync(self):
        self.thread = LoadThread()
        self.thread.start()

    def stop_sync(self):
        self.thread.stop()
        self.thread.join()

    def permission_added(self, node, permission, server_id):
        try:
            with session_scope() as session:
                node_type, identifier = self.get_node_type_and_identifier(node)
                permission_obj = get_or_create(session,
                                               PermissionObject,
                                               identifier=identifier,
                                               type=node_type)

                instance = Permission(object_id=permission_obj.id,
                                      server_id=server_id,
                                      node=permission)
                session.add(instance)
        except IntegrityError:
            pass

    def permission_removed(self, node, permission, server_id):
        with session_scope() as session:
            node_type, identifier = self.get_node_type_and_identifier(node)
            permission_obj = session.query(PermissionObject).filter_by(
                identifier=identifier, type=node_type).one()

            session.query(Permission).filter_by(object_id=permission_obj.id,
                                                server_id=server_id,
                                                node=permission).delete(False)

    def parent_added(self, node, parent_name):
        try:
            with session_scope() as session:
                node_type, identifier = self.get_node_type_and_identifier(node)
                child = get_or_create(session,
                                      PermissionObject,
                                      identifier=identifier,
                                      type=node_type)

                parent = get_or_create(session,
                                       PermissionObject,
                                       identifier=parent_name,
                                       type='Parent')

                parent_insert = parents_table.insert().values(
                    parent_id=parent.id, child_id=child.id)
                session.execute(parent_insert)
        except IntegrityError:
            pass

    def parent_removed(self, node, parent_name):
        with session_scope() as session:
            node_type, identifier = self.get_node_type_and_identifier(node)
            child = session.query(PermissionObject).filter_by(
                identifier=identifier, type=node_type).one()

            parent = session.query(PermissionObject).filter_by(
                identifier=parent_name, type='Parent').one()

            session.query(parents_table).filter_by(
                child_id=child.id, parent_id=parent.id).delete(False)

    @staticmethod
    def get_node_type_and_identifier(node):
        if isinstance(node, PlayerPermissions):
            result = ('Player', node.steamid64)
        elif isinstance(node, ParentPermissions):
            result = ('Parent', node.name)
        else:
            raise TypeError('Unexpected type "{}".'.format(
                type(node).__name__))

        return result
Beispiel #12
0
# =============================================================================
# >> ALL DECLARATION
# =============================================================================
# Add all the global variables to __all__
__all__ = [
    'DamageOffsets',
    'DamageTypes',
]


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
_entity_values = ConfigObj(
    SP_DATA_PATH.joinpath('entities', GAME_NAME + '.ini'), unrepr=True)


# =============================================================================
# >> CLASSES
# =============================================================================
class _ConstantBase(dict):
    '''Base constant class used to not allow setting values'''

    def __contains__(self, item):
        '''Override __contains__ to return whether the constant is valid'''
        return hasattr(self, item)

    def __getitem__(self, item):
        '''Override __getitem__ to return the attribute's value'''
        return self.__getattr__(item)
Beispiel #13
0
# Python Imports
#   SQLite3
from sqlite3 import connect

# Source.Python Imports
#   Events
from events.manager import event_manager
#   Paths
from paths import SP_DATA_PATH


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get the path to the user settings database file
_STORAGE_PATH = SP_DATA_PATH.joinpath('settings', 'users.db')

# Does the ../data/source-python/settings/ directory exist?
if not _STORAGE_PATH.parent.isdir():

    # Create the ../data/source-python/settings/ directory
    _STORAGE_PATH.parent.mkdir()


# =============================================================================
# >> CLASSES
# =============================================================================
class _UniqueSettings(dict):

    """Class used to interact with the database for a specific uniqueid."""
Beispiel #14
0
__all__ = ('ItemFlags',
           'MuzzleFlashStyle',
           'WeaponID',
           'WeaponProficiency',
           'WeaponSlot',
           'WeaponSound',
           'WeaponState',
           'WeaponType',
           )


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get the base path...
_path = SP_DATA_PATH.joinpath('weapons', 'constants')

# Get the MuzzleFlashStyle enumerator...
MuzzleFlashStyle = IntEnum('MuzzleFlashStyle', GameConfigObj(_path.joinpath(
    'MuzzleFlashStyle.ini')))

# Get the WeaponID enumerator...
WeaponID = IntEnum('WeaponID', GameConfigObj(_path.joinpath('WeaponID.ini')))

# Get the WeaponType enumerator...
WeaponType = IntEnum('WeaponType', GameConfigObj(_path.joinpath(
    'WeaponType.ini')))

# Get the WeaponSlot enumerator...
WeaponSlot = IntEnum('WeaponSlot', GameConfigObj(_path.joinpath(
    'WeaponSlot.ini')))
Beispiel #15
0

# =============================================================================
# >> ALL DECLARATION
# =============================================================================
__all__ = ('WeaponInfo',
           'weapon_scripts',
           )


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get the WeaponInfo class...
WeaponInfo = manager.create_type_from_dict('WeaponInfo', GameConfigObj(
    SP_DATA_PATH.joinpath('weapons', 'scripts', 'WeaponInfo.ini')))

# Get the _WeaponDatabase class...
try:
    from _weapons._scripts import _WeaponDatabase

    # Make sure the manager is able to find us...
    manager['_WeaponDatabase'] = _WeaponDatabase
except ImportError:
    _WeaponDatabase = manager.create_type_from_dict(
        '_WeaponDatabase', GameConfigObj(SP_DATA_PATH.joinpath(
            'weapons', 'scripts').joinpath('WeaponDatabase.ini')))

# Get the global _WeaponDatabase pointer...
manager.create_global_pointers_from_file(GameConfigObj(
    SP_DATA_PATH.joinpath('weapons', 'scripts', 'global_pointers.ini')))
Beispiel #16
0
from players.helpers import address_from_playerinfo
from players.helpers import basehandle_from_playerinfo
from players.helpers import edict_from_playerinfo
from players.helpers import index_from_playerinfo
from players.helpers import inthandle_from_playerinfo
from players.helpers import pointer_from_playerinfo
from players.helpers import uniqueid_from_playerinfo
from players.helpers import userid_from_playerinfo


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get the team's file for the current game
_game_teams = ConfigObj(
    SP_DATA_PATH.joinpath('players', 'teams', GAME_NAME + '.ini'), unrepr=True)


# =============================================================================
# >> MAIN PLAYER ITER CLASSES
# =============================================================================
class _PlayerIterManager(_BaseFilterManager):
    '''Filter management class specifically for player iterating'''

# Get the _PlayerIterManager instance
PlayerIterManager = _PlayerIterManager()


@public
class PlayerIter(_IterObject):
    '''Player iterate class'''
Beispiel #17
0
import sys

# Source.Python Imports
from core import GAME_NAME
from paths import DATA_PATH
from paths import SP_DATA_PATH
#   Memory
from memory import MemoryLogger
from memory.signature import Signature


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Store the game's ini file's path
_inipath = SP_DATA_PATH.joinpath('memory', GAME_NAME)

# Get the sp.memory.dictionary logger
MemoryDictionaryLogger = MemoryLogger.dictionary


# =============================================================================
# >> CLASSES
# =============================================================================
class _SignatureDictionary(dict):
    '''Dictionary to store Signature instances by name'''

    def parse_signature_ini(self, inifile):
        '''Parse an ini file and add its signatures to the dictionary'''

        # Get the ConfigObj instance of the file
Beispiel #18
0
# Site Package Imports
#   Configobj
from configobj import ConfigObj

# Source.Python Imports
from core import GAME_NAME
from paths import SP_DATA_PATH
#   DynCall
from dyncall.signature import Signature


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Store the game's ini file's path
_inipath = SP_DATA_PATH.joinpath('dyncall', GAME_NAME)


# =============================================================================
# >> CLASSES
# =============================================================================
class _SignatureDictionary(dict):
    '''Dictionary to store Signature instances by name'''

    def parse_signature_ini(self, inifile):
        '''Parse an ini file and add its signatures to the dictionary'''

        # Get the ConfigObj instance of the file
        sigs = ConfigObj(inifile)

        # Loop through all functions
Beispiel #19
0
        # Get the shortname for the given language
        language = self.get_language(language)

        # Was a language returned?
        if not language is None:

            # Set the default language
            self.default = language

    def get_language(self, language):
        '''Returns the shortname for the given language'''

        # Is the given language an item in the dictionary?
        if language in self:

            # Return the language's shortname
            return self[language]

        # Is the given language a known shortname?
        if language in self.values():

            # Return the shortname
            return language

        # If the value is not found, return None
        return None

# Get the _LanguageManager instance for the server's languages file
LanguageManager = _LanguageManager(SP_DATA_PATH.joinpath('languages.ini'))
Beispiel #20
0
from _messages import DialogType


# =============================================================================
# >> ALL DECLARATION
# =============================================================================
__all__ = ('DialogType',
           )


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get the sp.messages logger
messages_logger = _sp_logger.messages


# ============================================================================
# >> INITIALIZATION
# ============================================================================
# Loop trough all message classes
for message_name, message_class in _UserMessages(SP_DATA_PATH.joinpath(
    'messages', 'usermessages.ini'), SP_DATA_PATH.joinpath(
        'messages', 'games', GAME_NAME + '.ini')).items():

    # Globalize the current message class
    globals()[message_name] = message_class

    # Add the object, by name, to __all__
    __all__ = tuple(sorted(list(__all__) + [message_name]))
Beispiel #21
0
#   Memory
from memory import Convention
from memory import DataType
from memory import get_object_pointer
from memory.helpers import Type
from memory.manager import CustomType
from memory.manager import TypeManager
#   Paths
from paths import SP_DATA_PATH


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Get all of the necessary paths
_managers_path = SP_DATA_PATH.joinpath('entities')

# Store all supported types
_supported_descriptor_types = {
    FieldType.BOOLEAN: 'bool',
    FieldType.CHARACTER: 'uchar',
    FieldType.CLASSPTR: 'pointer',
    FieldType.COLOR32: 'Color',
    FieldType.EDICT: 'Edict',
    FieldType.EHANDLE: 'int',
    FieldType.FLOAT: 'float',
    FieldType.FUNCTION: 'pointer',
    FieldType.INTEGER: 'int',
    FieldType.INTERVAL: 'Interval',
    FieldType.MODELINDEX: 'uint',
    FieldType.MODELNAME: 'string_pointer',
Beispiel #22
0
                (Key.SRV_CHECK, Key.as_bool, True),
            )
        )

        # Create the global pointer objects
        for name, data in pointers:
            cls = self.get_class(name)
            if cls is None:
                raise NameError('Unknown class "{0}".'.format(name))

            self.global_pointer(cls, *data)

    def get_global_pointer(self, name):
        """Return the global pointer for the given class."""
        # Allow passing class objects
        if not isinstance(name, str):
            name = name.__name__

        # Raise an error if no global pointer was found.
        if name not in self.global_pointers:
            raise NameError('No global pointer found for "{0}".'.format(name))

        return self.global_pointers[name]

# Create a shared manager instance
manager = TypeManager()

# Parse our global pointers...
manager.create_global_pointers_from_file(GameConfigObj(
    SP_DATA_PATH.joinpath('memory', 'global_pointers.ini')))
Beispiel #23
0
from core import GAME_NAME
from paths import SP_DATA_PATH


# =============================================================================
# >> ALL DECLARATION
# =============================================================================
# Set all to an empty list
__all__ = []


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Store the base "keyvalues" path
_basepath = SP_DATA_PATH.joinpath('keyvalues')


# =============================================================================
# >> CLASSES
# =============================================================================
class _KeyValues(dict):
    '''Dictionary that stores all entities with their keyvalues'''

    def __missing__(self, item):
        '''Called the first time an entity is added to the dictionary'''

        # Get all keyvalues for the given entity
        value = self[item] = _get_all_entity_keyvalues(item)

        # Return the keyvalues
Beispiel #24
0
#   DynCall
from dyncall.dictionary import SignatureDictionary


# =============================================================================
# >> ALL DECLARATION
# =============================================================================
# Set all to an empty list
__all__ = []


# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Store the base "functions" path
_basepath = SP_DATA_PATH.joinpath('functions')


# =============================================================================
# >> CLASSES
# =============================================================================
class _Functions(dict):
    '''Dictionary that stores all entities with their functions'''

    def __missing__(self, item):
        '''Called the first time an entity is added to the dictionary'''

        # Get all functions for the given entity
        value = self[item] = _get_all_entity_functions(item)

        # Return the functions