Ejemplo n.º 1
0
def raceinfo_skills_single_menu_build(menu, client):
    menu.clear()

    wcsplayer = Player(client)
    name = wcsplayer.data['_internal_raceinfo']
    settings = race_manager[name]

    menu.title.tokens['name'] = settings.strings['name']

    current_skill = wcsplayer.data.get('_internal_raceinfo_viewing_skill')

    i = 1

    for name in settings.config['skills']:
        events = settings.config['skills'][name]['event']

        if 'player_ultimate' in events:
            option = PagedOption(menu_strings['raceinfo_skills_menu ultimate'],
                                 name)
            option.text.tokens['name'] = settings.strings[name]
        elif 'player_ability' in events:
            option = PagedOption(menu_strings['raceinfo_skills_menu ability'],
                                 name)
            option.text.tokens['name'] = settings.strings[name]
        elif 'player_ability_on' in events or 'player_ability_off' in events:
            option = PagedOption(
                menu_strings['raceinfo_skills_menu ability_on'], name)
            option.text.tokens['name'] = settings.strings[name]
            option.text.tokens['index'] = i

            i += 1
        else:
            option = PagedOption(settings.strings[name], name)

        # Perform translation of the ultimate/ability part right now, so we can append the description.
        option.text = option.text.get_string(get_client_language(client))

        if name == current_skill:
            kwargs = {}
            settings.execute('on_skill_desc', wcsplayer, name, kwargs)

            info = settings.strings[f'{name} description']

            if info:
                info = info.get_string(get_client_language(client), **kwargs)

                for text in wrap(info, 30):
                    option.text += '\n' + text

        menu.append(option)
Ejemplo n.º 2
0
def shopinfo_detail_menu_build(menu, client):
    wcsplayer = Player(client)
    item_name = wcsplayer.data['_internal_shopinfo']
    settings = item_manager[item_name]

    menu[0].text.tokens['name'] = settings.strings['name']
    menu[1].text.tokens['level'] = settings.config['required']
    menu[2].text.tokens['cost'] = settings.config['cost']
    menu[3].text = menu_strings[
        f'shopinfo_detail_menu line 3 {settings.config["dab"]}']
    menu[4].text = menu_strings[
        f'shopinfo_detail_menu line 4 {settings.config["duration"]}']

    for i, option in enumerate(menu[5:], 5):
        if isinstance(option, SimpleOption):
            del menu[5:i]
            break

    kwargs = {}

    settings.execute('on_item_desc', wcsplayer, kwargs)

    info = settings.strings['description']

    if info:
        info = info.get_string(get_client_language(client), **kwargs)

        for i, text in enumerate(wrap(info, 30), 5):
            menu.insert(i, text)

        for i in range(i + 1, MAX_ITEM_COUNT + 2):
            menu.insert(i, Text(' '))
    else:
        for i in range(i + 1, MAX_ITEM_COUNT + 2):
            menu.insert(i, Text(' '))
Ejemplo n.º 3
0
def raceinfo_race_detail_menu_build(menu, client):
    del menu[2:-3]

    wcsplayer = Player(client)
    race_name = wcsplayer.data['_internal_raceinfo']
    settings = race_manager[race_name]

    menu[0].text.tokens['name'] = settings.strings['name']

    kwargs = {}

    settings.execute('on_race_desc', wcsplayer, kwargs)

    info = settings.strings['description']

    if info:
        info = info.get_string(get_client_language(client), **kwargs)

        for i, text in enumerate(wrap(info, 30), 2):
            menu.insert(i, text)

        for i in range(i + 1, MAX_ITEM_COUNT + 2):
            menu.insert(i, Text(' '))
    else:
        for i in range(2, MAX_ITEM_COUNT + 2):
            menu.insert(i, Text(' '))
Ejemplo n.º 4
0
def _change_race(wcsplayer, value):
    found = []
    lower_search = value.lower()
    language = get_client_language(wcsplayer.index)

    for name, settings in race_manager.items():
        if lower_search == settings.strings['name'].get_string(language).lower():
            if name not in found:
                found.append(name)

    for name, settings in race_manager.items():
        if lower_search in settings.strings['name'].get_string(language).lower():
            if name not in found:
                found.append(name)

    for partial in [x.lower() for x in value.split()]:
        for name, settings in race_manager.items():
            if partial in settings.strings['name'].get_string(language).lower():
                if name not in found:
                    found.append(name)

    if found:
        wcsplayer.data['_internal_wcsadmin_changerace'] = found

        return wcsadmin_players_sub_changerace_menu
    else:
        return False
    def execute(self, client, left_player):
        if left_player.is_fake_client() or left_player.is_hltv():
            client.tell(plugin_strings['error bot_cannot_ban'])
            return

        ip_address = extract_ip_address(left_player.address)
        if banned_ip_address_manager.is_banned(ip_address):
            client.tell(plugin_strings['error already_ban_in_effect'])
            return

        try:
            player = Player.from_userid(left_player.userid)
        except (OverflowError, ValueError):
            pass
        else:
            language = get_client_language(player.index)

            # Disconnect the player
            player.kick(
                plugin_strings['default_ban_reason'].get_string(language))

        duration = int(plugin_config['settings']['default_ban_time_seconds'])

        GameThread(
            target=banned_ip_address_manager.save_ban_to_database,
            args=(client.steamid, ip_address, left_player.name, duration)
        ).start()

        for ws_ban_ip_address_page in _ws_ban_ip_address_pages:
            ws_ban_ip_address_page.send_remove_id(left_player)

        log_admin_action(plugin_strings['message banned'].tokenized(
            admin_name=client.name,
            player_name=left_player.name,
        ))
Ejemplo n.º 6
0
    def get_language(self):
        """Return the player's language.

        If the player is a bot, an empty string will be returned.

        :rtype: str
        """
        return get_client_language(self.index)
Ejemplo n.º 7
0
    def language(self):
        """Return the player's language.

        If the player is a bot, an empty string will be returned.

        :rtype: str
        """
        return get_client_language(self.index)
Ejemplo n.º 8
0
    def send(self, *args, **kwargs):
        """Send the message to the given users."""
        # Get a recipient filter of the given users
        recipient = RecipientFilter(*(args or self.users))

        # Any parameter to translate?
        if self._translatable_parameters:

            # Get a default dictionnary to store the players
            languages = defaultdict(set)

            # Get a mapping of the given tokens
            tokens = ChainMap(kwargs, self.tokens)

            # Loop through all indexes
            for index in recipient:

                if playerinfo_from_index(index).is_fake_client():
                    continue

                # Add the current index
                languages[get_client_language(index)].add(index)

            # Loop through all languages
            for language, users in languages.items():

                # Get a dictionnary to store the translated strings
                translated_parameters = dict()

                # Loop through all translatable parameter
                for parameter_name in self._translatable_parameters:

                    # Get the current parameter value
                    parameter_value = self[parameter_name]

                    # Is the current parameter not translatable?
                    if not isinstance(parameter_value, TranslationStrings):

                        # No need to go further
                        continue

                    # Translate the current parameter
                    translated_parameters[
                        parameter_name] = parameter_value.get_string(
                        language, **tokens)

                # Update the recipient filter
                recipient.update(*users)

                # Send the message
                self._send_message(
                    recipient, **ChainMap(translated_parameters, self))

        # Otherwise
        else:

            # Send the message
            self._send_message(recipient, **self)
Ejemplo n.º 9
0
def _translate_text(text, player_index):
    """Translate <text> if it is an instance of TranslationStrings.

    Otherwise the original text will be returned.
    """
    if isinstance(text, TranslationStrings):
        return text.get_string(get_client_language(player_index))

    return text
    def execute(self, client, player):
        language = get_client_language(player.index)
        player_name = player.name

        player.kick(plugin_strings['default_kick_reason'].get_string(language))

        log_admin_action(plugin_strings['message kicked'].tokenized(
            admin_name=client.name,
            player_name=player_name,
        ))
Ejemplo n.º 11
0
def _translate_text(text, player_index):
    """Translate the given ``text``.

    Only translate if ``text`` is an instance of
    :class:`translations.strings.TranslationStrings`. Otherwise the original
    text will be returned.
    """
    if isinstance(text, TranslationStrings):
        return text.get_string(get_client_language(player_index))

    return text
Ejemplo n.º 12
0
def _translate_text(text, player_index):
    """Translate the given ``text``.

    Only translate if ``text`` is an instance of
    :class:`translations.strings.TranslationStrings`. Otherwise the original
    text will be returned.
    """
    if isinstance(text, TranslationStrings):
        return text.get_string(get_client_language(player_index))

    return text
Ejemplo n.º 13
0
        def select_callback(admin):
            lines = []
            players = get_players_to_play()
            language = get_client_language(admin.player.index)

            def translated(caption):
                if isinstance(caption, str):
                    return caption

                return caption.tokenize(**COLOR_SCHEME).get_string(language)

            for i, game_class in enumerate(_available_game_classes, start=1):
                lines.append("{}. *** GAME CLASS: {} (caption: {}) ***".format(
                    i,
                    game_class.__name__,
                    translated(game_class.caption),
                ))

                lines.append("Available launchers for the "
                             "current number of alive "
                             "prisoners ({}):".format(len(players)))

                for j, game_launcher in enumerate(
                        game_class.get_available_launchers(
                            admin.player, players),
                        start=1):

                    lines.append("{}.{}. {}".format(
                        i, j, translated(game_launcher.caption)))

                    denial_reason = game_launcher.get_launch_denial_reason(
                        admin.player, players)

                    if denial_reason is not None:
                        denial_reason = translated(denial_reason)

                    lines.append(
                        "Launch denial reason: {}".format(denial_reason))

                lines.append("")

            try:
                with open(ARCJAIL_LOG_PATH / "available-games.txt", "w") as f:
                    f.write("\n".join(lines))

                tell(
                    admin.player,
                    strings_module['arcadmin dump_available_games saved'].
                    tokenize(file=ARCJAIL_LOG_PATH / "available-games.txt"))

            except OSError:
                tell(admin.player,
                     strings_module['arcadmin dump_available_games failed'])
Ejemplo n.º 14
0
    def _categorize_players_by_language(player_indexes):
        """Categorize players by their language.

        Return a dict in the following format:
        {<language>: set([<player index>, ...])}
        """
        languages = collections.defaultdict(set)
        for index in player_indexes:
            if playerinfo_from_index(index).is_fake_client():
                # No need to send a user message to bots
                continue

            languages[get_client_language(index)].add(index)

        return languages
Ejemplo n.º 15
0
    def _categorize_players_by_language(player_indexes):
        """Categorize players by their language.

        Return a dict in the following format:
        {<language>: set([<player index>, ...])}
        """
        languages = collections.defaultdict(set)
        for index in player_indexes:
            if playerinfo_from_index(index).is_fake_client():
                # No need to send a user message to bots
                continue

            languages[get_client_language(index)].add(index)

        return languages
        def on_data_received(self, data):
            if 'spa_action' not in data:
                self.on_page_data_received(data)
                return

            client = clients[self.index]
            language = get_client_language(client.player.index)

            nav_data = {
                'navData': self._extract_nav_data(main_motd, client, language),
                'currentPath': self.nav_path,
            }
            nav_init_b64 = b64encode(
                json.dumps(nav_data).encode('utf-8')).decode('utf-8')

            if data['spa_action'] == "init":
                self.send_data({
                    'admin_version': info.version,
                    'admin_author': info.author,
                    'server_time': time(),
                    'nav_init_b64': nav_init_b64,
                })
                return
Ejemplo n.º 17
0
def send_page(player):
    language = get_client_language(player.index)

    # /su
    def su_callback(data, error):
        pass

    def su_retargeting_callback(new_page_id):
        if new_page_id == "su-offline-items":
            return (su_offline_items_callback,
                    su_offline_items_retargeting_callback)

        if new_page_id == "su-online-items":
            return (su_online_items_callback,
                    su_online_items_retargeting_callback)

        return None

    # /su-offline-items
    def su_offline_items_callback(data, error):
        pass

    def su_offline_items_retargeting_callback(new_page_id):
        if new_page_id == "ajax-su-offline-items":
            return (ajax_su_offline_items_callback,
                    ajax_su_offline_items_retargeting_callback)

        return None

    # /ajax-su-offline-items
    def ajax_su_offline_items_callback(data, error):
        db_session = Session()

        db_arcjail_user = db_session.query(
            DB_ArcjailUser).filter_by(steamid=data['steamid']).first()

        if db_arcjail_user is None:
            db_session.close()

            error = strings_module['su_offline_items steamid_not_found']
            return {
                'popup_error': error.get_string(language),
            }

        if data['action'] == "view-inventory":
            inventory_items = []

            for item_id in json.loads(db_arcjail_user.slot_data):
                db_item = db_session.query(DB_Item).filter_by(
                    id=item_id).first()

                if db_item is None:
                    continue

                item_instance = item_classes[db_item.class_id][
                    db_item.instance_id]

                item_json = {
                    'class_id': item_instance.class_id,
                    'instance_id': item_instance.instance_id,
                    'caption': item_instance.caption.get_string(language),
                    'description': item_instance.description.get_string(
                        language),

                    'icon': item_instance['icon'],
                    'amount': db_item.amount,
                }

                for stat_name in ('stat_max_per_slot',
                                  'stat_team_restriction',
                                  'stat_manual_activation',
                                  'stat_auto_activation',
                                  'stat_max_sold_per_round',
                                  'stat_price'):

                    stat = getattr(item_instance, stat_name)
                    if stat is None:
                        item_json[stat_name] = None
                    else:
                        item_json[stat_name] = stat.get_string(language)

                inventory_items.append(item_json)

            db_session.close()

            notify = strings_module['su_offline_items inventory_loaded']
            return {
                'account': db_arcjail_user.account,
                'account_formatted': "{:,}".format(db_arcjail_user.account),
                'inventory_items': inventory_items,
                'popup_notify': notify.get_string(language),
            }

        if data['action'] == "give-item":
            try:
                item_classes[data['class_id']][data['instance_id']]
            except KeyError:
                db_session.close()

                error = strings_module['su_offline_items unknown_item']
                return {
                    'popup_error': error.get_string(language),
                }

            slot_data = json.loads(db_arcjail_user.slot_data)
            for item_id in slot_data:
                db_item = db_session.query(DB_Item).filter_by(
                    id=item_id).first()

                if db_item is None:
                    continue

                if (db_item.class_id, db_item.instance_id) == (
                        data['class_id'], data['instance_id']):

                    db_item.amount += data['amount']
                    break

            else:
                db_item = DB_Item()
                db_item.class_id = data['class_id']
                db_item.instance_id = data['instance_id']
                db_item.amount = data['amount']
                db_item.current_owner = data['steamid']

                db_session.add(db_item)
                db_session.commit()

                slot_data.append(db_item.id)
                db_arcjail_user.slot_data = json.dumps(slot_data)

            db_session.commit()
            db_session.close()

            notify = strings_module['su_offline_items item_given']
            return {
                'popup_notify': notify.get_string(language),
            }

    def ajax_su_offline_items_retargeting_callback(new_page_id):
        if new_page_id == "su":
            return su_callback, su_retargeting_callback

        return None

    # /su-online-items
    def su_online_items_callback(data, error):
        pass

    def su_online_items_retargeting_callback(new_page_id):
        if new_page_id == "ajax-su-online-items":
            return (ajax_su_online_items_callback,
                    ajax_su_online_items_retargeting_callback)

        return None

    # /ajax-su-online-items
    def ajax_su_online_items_callback(data, error):
        pass   # TODO: Implement

    def ajax_su_online_items_retargeting_callback(new_page_id):
        if new_page_id == "su":
            return su_callback, su_retargeting_callback

        return None

    plugin_instance.send_page(
        player, 'su', su_callback, su_retargeting_callback)
Ejemplo n.º 18
0
 def __init__(self, player):
     self.player = player
     self._counters = []
     self._pre_protection_health = None
     self._language = get_client_language(player.index)
     self.dead = player.dead
Ejemplo n.º 19
0
    def json_shop_callback(data, error):
        from ..inventory import strings_module as strings_inventory
        from ..shop import config_manager, strings_module as strings_shop

        if error is not None:
            return

        language = get_client_language(player.index)
        popup_notify = popup_error = None

        if data['action'] in ("buy", "use"):
            class_id = data['class_id']
            instance_id = data['instance_id']

            item_instance = get_item_instance(class_id, instance_id)

            # Is it known item?
            if item_instance is None:
                return {'error': "APPERR_UNKNOWN_ITEM"}

            if data['action'] == "buy":
                # Does player have enough credits to buy it?
                if item_instance['price'] > arcjail_user.account:
                    return {'error': "APPERR_TOO_EXPENSIVE"}

                item = arcjail_user.get_item_by_instance_id(
                    class_id, instance_id)

                # Maybe players already has too many of these items?
                amount = 0 if item is None else item.amount
                max_per_slot = item_instance.get('max_per_slot', -1)

                if -1 < max_per_slot <= amount:
                    return {'error': "APPERR_MAX_PER_SLOT_LIMIT"}

                # Does player's team fit requirements?
                if player.team not in item_instance.team_restriction:
                    return {'error': "APPERR_WRONG_TEAM"}

                # Item-specific checks
                reason = item_instance.get_purchase_denial_reason(player, 1)
                if reason is not None:
                    popup_error = reason

                else:
                    # Ok, let's sell it
                    spend_credits(
                        player,
                        item_instance['price'],
                        strings_shop['credits_reason'].tokenize(
                            item=item_instance.caption.get_string(language),
                        )
                    )

                    item = arcjail_user.give_item(
                        class_id, instance_id, async=False)

                    if config_manager['checkout_sound'] is not None:
                        config_manager['checkout_sound'].play(player.index)

                    if item_instance.auto_activation:
                        reason = item_instance.try_activate(
                            player, item.amount - 1, async=False)

                        if reason is not None:
                            popup_error = reason

                        arcjail_user.take_item(item, amount=1, async=False)

                    popup_notify = strings_shop[
                        'popup_notify purchased'].tokenize(
                            caption=item_instance.caption)

            elif data['action'] == "use":
                if not item_instance.manual_activation:
                    return {'error': "APPERR_NO_MANUAL_ACTIVATION"}

                if player.dead and item_instance.use_only_when_alive:
                    return {'error': "APPERR_DEAD"}

                if player.team not in item_instance.use_team_restriction:
                    return {'error': "APPERR_WRONG_TEAM"}

                item = arcjail_user.get_item_by_instance_id(
                    class_id, instance_id)

                if item is None:
                    return {'error': "APPERR_DOES_NOT_BELONG_TO_PLAYER"}

                reason = item_instance.try_activate(
                    player, item.amount - 1, async=False)

                if reason is not None:
                    popup_error = reason

                else:
                    arcjail_user.take_item(item, amount=1, async=False)

                    popup_notify = strings_inventory[
                        'popup_notify activated'].tokenize(
                            caption=item.class_.caption)

        shop_items = []
        inventory_items = []

        # Shop
        for item_instance in iter_item_instance_classes():
            if item_instance.get('hide_from_shop', False):
                continue

            item_json = {
                'class_id': item_instance.class_id,
                'instance_id': item_instance.instance_id,
                'category_id': item_instance.category_id,
                'caption': item_instance.caption.get_string(language),
                'description': item_instance.description.get_string(language),
                'price': item_instance['price'],
                'icon': item_instance['icon'],
                'cannot_buy_reason': None,
            }

            # Maybe players already has too many of these items?
            item = arcjail_user.get_item_by_instance_id(
                item_instance.class_id, item_instance.instance_id)

            amount = 0 if item is None else item.amount
            max_per_slot = item_instance.get('max_per_slot', -1)

            if -1 < max_per_slot <= amount:
                item_json['cannot_buy_reason'] = \
                    strings_shop['cannot_buy max_per_slot'].get_string(
                        language)

            # Does player's team fit requirements?
            if player.team not in item_instance.team_restriction:
                item_json['cannot_buy_reason'] = \
                    strings_shop['cannot_buy team_restriction'].get_string(
                        language)

            # Get stat values
            for stat_name in ('stat_max_per_slot',
                              'stat_team_restriction',
                              'stat_manual_activation',
                              'stat_auto_activation',
                              'stat_max_sold_per_round',
                              'stat_price'):

                stat = getattr(item_instance, stat_name)
                if stat is None:
                    item_json[stat_name] = None
                else:
                    item_json[stat_name] = stat.get_string(language)

            shop_items.append(item_json)

        # Inventory
        for item in arcjail_user.iter_all_items():
            item_json = {
                'class_id': item.class_.class_id,
                'instance_id': item.class_.instance_id,
                'category_id': item.class_.category_id,
                'caption': item.class_.caption.get_string(language),
                'description': item.class_.description.get_string(language),
                'icon': item.class_['icon'],
                'amount': item.amount,
                'cannot_use_reason': None,
            }

            # Does player's team fit requirements?
            if player.team not in item.class_.use_team_restriction:
                item_json['cannot_use_reason'] = \
                    strings_inventory[
                        'cannot_buy team_restriction'].get_string(language)

            # Does this item allow manual activation?
            if not item.class_.manual_activation:
                item_json['cannot_use_reason'] = \
                    strings_inventory[
                        'cannot_use no_manual_activation'].get_string(
                            language)

            # Is the player dead and item only allows activation by the alive?
            if player.dead and item.class_.use_only_when_alive:
                item_json['cannot_use_reason'] = \
                    strings_inventory['cannot_use dead'].get_string(language)

            # Get stat values
            for stat_name in ('stat_max_per_slot',
                              'stat_team_restriction',
                              'stat_manual_activation',
                              'stat_auto_activation',
                              'stat_max_sold_per_round',
                              'stat_price'):

                stat = getattr(item.class_, stat_name)
                if stat is None:
                    item_json[stat_name] = None
                else:
                    item_json[stat_name] = stat.get_string(language)

            inventory_items.append(item_json)

        categories = []
        for category_id, category in sorted(
                item_categories_json.items(),
                key=lambda items: items[1]['position']):

            categories.append({
                'id': category_id,
                'caption': strings_inventory[category['caption']].get_string(
                    language),
                'hide_from_shop': category.get('hide_from_shop', False)
            })

        if popup_notify is not None:
            popup_notify = popup_notify.get_string(language)

        if popup_error is not None:
            popup_error = popup_error.get_string(language)

        return {
            'account': arcjail_user.account,
            'account_formatted': "{:,}".format(arcjail_user.account),
            'shop_items': shop_items,
            'inventory_items': inventory_items,
            'popup_notify': popup_notify,
            'popup_error': popup_error,
            'categories': categories,
        }
Ejemplo n.º 20
0
 def __init__(self, player):
     self.player = player
     self._counters = []
     self._pre_protection_health = None
     self._language = get_client_language(player.index)
     self.dead = player.dead
Ejemplo n.º 21
0
        playerinfo_from_edict(edict)))
_player_iter_manager.register_return_type(
    'playerinfo', playerinfo_from_edict)
_player_iter_manager.register_return_type(
    'player', lambda edict: PlayerEntity(
        index_from_edict(edict)))
_player_iter_manager.register_return_type(
    'name', lambda edict: playerinfo_from_edict(edict).get_name())
_player_iter_manager.register_return_type(
    'steamid', lambda edict: playerinfo_from_edict(
        edict).get_networkid_string())
_player_iter_manager.register_return_type(
    'location', lambda edict: playerinfo_from_edict(edict).get_abs_origin())
_player_iter_manager.register_return_type(
    'kills', lambda edict: playerinfo_from_edict(edict).get_frag_count())
_player_iter_manager.register_return_type(
    'deaths', lambda edict: playerinfo_from_edict(edict).get_death_count())
_player_iter_manager.register_return_type(
    'model', lambda edict: Model(
        playerinfo_from_edict(edict).get_model_name()))
_player_iter_manager.register_return_type(
    'health', lambda edict: playerinfo_from_edict(edict).get_health())
_player_iter_manager.register_return_type(
    'armor', lambda edict: playerinfo_from_edict(edict).get_armor_value())
_player_iter_manager.register_return_type(
    'weapon', lambda edict: playerinfo_from_edict(edict).get_weapon_name())
_player_iter_manager.register_return_type(
    'language', lambda edict: get_client_language(index_from_edict(edict)))
_player_iter_manager.register_return_type(
    'team', lambda edict: playerinfo_from_edict(edict).get_team_index())
Ejemplo n.º 22
0
 def language(self):
     """Return the player's language."""
     return get_client_language(self.index)
Ejemplo n.º 23
0
    def json_inventory_callback(data, error):
        from ..inventory import (
            inventory_ad_lines_ids, strings_module as strings_inventory)

        if error is not None:
            return

        language = get_client_language(player.index)
        popup_notify = popup_error = None

        if data['action'] == "use":
            class_id = data['class_id']
            instance_id = data['instance_id']

            item_instance = get_item_instance(class_id, instance_id)

            # Is it known item?
            if item_instance is None:
                return {'error': "APPERR_UNKNOWN_ITEM"}

            if not item_instance.manual_activation:
                return {'error': "APPERR_NO_MANUAL_ACTIVATION"}

            if player.dead and item_instance.use_only_when_alive:
                return {'error': "APPERR_DEAD"}

            if player.team not in item_instance.use_team_restriction:
                return {'error': "APPERR_WRONG_TEAM"}

            item = arcjail_user.get_item_by_instance_id(
                class_id, instance_id)

            if item is None:
                return {'error': "APPERR_DOES_NOT_BELONG_TO_PLAYER"}

            reason = item_instance.try_activate(
                player, item.amount - 1, async=False)

            if reason is not None:
                popup_error = reason

            else:
                arcjail_user.take_item(item, amount=1, async=False)

                popup_notify = strings_inventory[
                    'popup_notify activated'].tokenize(
                        caption=item.class_.caption)

        inventory_items = []

        # Inventory
        for item in arcjail_user.iter_all_items():
            item_json = {
                'class_id': item.class_.class_id,
                'instance_id': item.class_.instance_id,
                'category_id': item.class_.category_id,
                'caption': item.class_.caption.get_string(language),
                'description': item.class_.description.get_string(language),
                'icon': item.class_['icon'],
                'amount': item.amount,
                'cannot_use_reason': None,
            }

            # Does player's team fit requirements?
            if player.team not in item.class_.use_team_restriction:
                item_json['cannot_use_reason'] = \
                    strings_inventory[
                        'cannot_use team_restriction'].get_string(language)

            # Does this item allow manual activation?
            if not item.class_.manual_activation:
                item_json['cannot_use_reason'] = \
                    strings_inventory[
                        'cannot_use no_manual_activation'].get_string(language)

            # Is the player dead and item only allows activation by the alive?
            if player.dead and item.class_.use_only_when_alive:
                item_json['cannot_use_reason'] = \
                    strings_inventory['cannot_use dead'].get_string(
                        language)

            # Get stat values
            for stat_name in ('stat_max_per_slot',
                              'stat_team_restriction',
                              'stat_manual_activation',
                              'stat_auto_activation',
                              'stat_max_sold_per_round',
                              'stat_price'):

                stat = getattr(item.class_, stat_name)
                if stat is None:
                    item_json[stat_name] = None
                else:
                    item_json[stat_name] = stat.get_string(language)

            inventory_items.append(item_json)

        categories = []
        for category_id, category in sorted(
                item_categories_json.items(),
                key=lambda items: items[1]['position']):
            categories.append({
                'id': category_id,
                'caption': strings_inventory[category['caption']].get_string(
                    language),
            })

        inventory_ad_lines = []
        for inventory_ad_lines_id in inventory_ad_lines_ids:
            inventory_ad_lines.append(
                strings_inventory[inventory_ad_lines_id].get_string(language))

        if popup_notify is not None:
            popup_notify = popup_notify.get_string(language)

        if popup_error is not None:
            popup_error = popup_error.get_string(language)

        return {
            'account': arcjail_user.account,
            'account_formatted': "{:,}".format(arcjail_user.account),
            'inventory_items': inventory_items,
            'popup_notify': popup_notify,
            'popup_error': popup_error,
            'categories': categories,
            'inventory_ad_lines': inventory_ad_lines,
        }
Ejemplo n.º 24
0
        def select_callback(admin):
            lines = []
            players = get_players_to_play()
            language = get_client_language(admin.player.index)

            def translated(caption):
                if isinstance(caption, str):
                    return caption

                return caption.tokenize(**COLOR_SCHEME).get_string(language)

            for i, game_class in enumerate(_available_game_classes, start=1):
                lines.append(
                    "{}. *** GAME CLASS: {} (caption: {}) ***".format(
                        i,
                        game_class.__name__,
                        translated(game_class.caption),
                    )
                )

                lines.append("Available launchers for the "
                             "current number of alive "
                             "prisoners ({}):".format(len(players)))

                for j, game_launcher in enumerate(
                    game_class.get_available_launchers(
                        admin.player, players
                    ),
                    start=1
                ):

                    lines.append("{}.{}. {}".format(
                        i, j, translated(game_launcher.caption)))

                    denial_reason = game_launcher.get_launch_denial_reason(
                        admin.player, players)

                    if denial_reason is not None:
                        denial_reason = translated(denial_reason)

                    lines.append("Launch denial reason: {}".format(
                        denial_reason
                    ))

                lines.append("")

            try:
                with open(ARCJAIL_LOG_PATH / "available-games.txt", "w") as f:
                    f.write("\n".join(lines))

                tell(
                    admin.player,
                    strings_module[
                        'arcadmin dump_available_games saved'
                    ].tokenize(
                        file=ARCJAIL_LOG_PATH / "available-games.txt"
                    )
                )

            except OSError:
                tell(admin.player,
                     strings_module['arcadmin dump_available_games failed'])
Ejemplo n.º 25
0
def send_page(player):
    language = get_client_language(player.index)

    # /su
    def su_callback(data, error):
        pass

    def su_retargeting_callback(new_page_id):
        if new_page_id == "su-offline-items":
            return (su_offline_items_callback,
                    su_offline_items_retargeting_callback)

        if new_page_id == "su-online-items":
            return (su_online_items_callback,
                    su_online_items_retargeting_callback)

        return None

    # /su-offline-items
    def su_offline_items_callback(data, error):
        pass

    def su_offline_items_retargeting_callback(new_page_id):
        if new_page_id == "ajax-su-offline-items":
            return (ajax_su_offline_items_callback,
                    ajax_su_offline_items_retargeting_callback)

        return None

    # /ajax-su-offline-items
    def ajax_su_offline_items_callback(data, error):
        db_session = Session()

        db_arcjail_user = db_session.query(DB_ArcjailUser).filter_by(
            steamid=data['steamid']).first()

        if db_arcjail_user is None:
            db_session.close()

            error = strings_module['su_offline_items steamid_not_found']
            return {
                'popup_error': error.get_string(language),
            }

        if data['action'] == "view-inventory":
            inventory_items = []

            for item_id in loads(db_arcjail_user.slot_data):
                db_item = db_session.query(DB_Item).filter_by(
                    id=item_id).first()

                if db_item is None:
                    continue

                item_instance = item_classes[db_item.class_id][
                    db_item.instance_id]

                item_json = {
                    'class_id': item_instance.class_id,
                    'instance_id': item_instance.instance_id,
                    'caption': item_instance.caption.get_string(language),
                    'description':
                    item_instance.description.get_string(language),
                    'icon': item_instance['icon'],
                    'amount': db_item.amount,
                }

                for stat_name in ('stat_max_per_slot', 'stat_team_restriction',
                                  'stat_manual_activation',
                                  'stat_auto_activation',
                                  'stat_max_sold_per_round', 'stat_price'):

                    stat = getattr(item_instance, stat_name)
                    if stat is None:
                        item_json[stat_name] = None
                    else:
                        item_json[stat_name] = stat.get_string(language)

                inventory_items.append(item_json)

            db_session.close()

            notify = strings_module['su_offline_items inventory_loaded']
            return {
                'account': db_arcjail_user.account,
                'account_formatted': "{:,}".format(db_arcjail_user.account),
                'inventory_items': inventory_items,
                'popup_notify': notify.get_string(language),
            }

        if data['action'] == "give-item":
            try:
                item_classes[data['class_id']][data['instance_id']]
            except KeyError:
                db_session.close()

                error = strings_module['su_offline_items unknown_item']
                return {
                    'popup_error': error.get_string(language),
                }

            slot_data = loads(db_arcjail_user.slot_data)
            for item_id in slot_data:
                db_item = db_session.query(DB_Item).filter_by(
                    id=item_id).first()

                if db_item is None:
                    continue

                if (db_item.class_id,
                        db_item.instance_id) == (data['class_id'],
                                                 data['instance_id']):

                    db_item.amount += data['amount']
                    break

            else:
                db_item = DB_Item()
                db_item.class_id = data['class_id']
                db_item.instance_id = data['instance_id']
                db_item.amount = data['amount']
                db_item.current_owner = data['steamid']

                db_session.add(db_item)
                db_session.commit()

                slot_data.append(db_item.id)
                db_arcjail_user.slot_data = dumps(slot_data)

            db_session.commit()
            db_session.close()

            notify = strings_module['su_offline_items item_given']
            return {
                'popup_notify': notify.get_string(language),
            }

    def ajax_su_offline_items_retargeting_callback(new_page_id):
        if new_page_id == "su":
            return su_callback, su_retargeting_callback

        return None

    # /su-online-items
    def su_online_items_callback(data, error):
        pass

    def su_online_items_retargeting_callback(new_page_id):
        if new_page_id == "ajax-su-online-items":
            return (ajax_su_online_items_callback,
                    ajax_su_online_items_retargeting_callback)

        return None

    # /ajax-su-online-items
    def ajax_su_online_items_callback(data, error):
        pass  # TODO: Implement

    def ajax_su_online_items_retargeting_callback(new_page_id):
        if new_page_id == "su":
            return su_callback, su_retargeting_callback

        return None

    plugin_instance.send_page(player, 'su', su_callback,
                              su_retargeting_callback)
    def on_page_data_received(self, data):
        client = clients[self.index]

        if data['action'] == "execute":
            ban_id = data['banId']
            reason = data['reason']
            duration = data['duration']

            banned_player_info = self._get_ban_by_id(client, ban_id)
            if banned_player_info is None:

                # Might just as well log the ban id and the client, looks like
                # this client has tried to lift somebody else's ban
                return

            client.sync_execution(self.feature.execute, (
                client, banned_player_info, reason, duration))

            self.send_data({
                'feature-executed': "scheduled"
            })
            return

        if data['action'] == "get-ban-data":
            language = get_client_language(self.index)

            ban_durations = []
            for stock_ban_duration in stock_ban_durations:
                ban_durations.append({
                    'value': stock_ban_duration,
                    'title': format_ban_duration(
                        stock_ban_duration).get_string(language),
                })

            ban_reasons = []
            for stock_ban_reason in stock_ban_reasons.values():
                duration_value = stock_ban_reason.duration
                duration_title = (
                    None if duration_value is None else
                    format_ban_duration(duration_value).get_string(language))

                ban_reasons.append({
                    'hidden': stock_ban_reason.translation.get_string(
                                language_manager.default),
                    'title': stock_ban_reason.translation.get_string(language),
                    'duration-value': duration_value,
                    'duration-title': duration_title,
                })

            ban_data = []
            for banned_player_info in self._get_bans(client):
                ban_data.append({
                    'uniqueid': str(banned_player_info.uniqueid),
                    'banId': banned_player_info.id,
                    'name': banned_player_info.name,
                })

            self.send_data({
                'action': "ban-data",
                'bans': ban_data,
                'reasons': ban_reasons,
                'durations': ban_durations,
            })