示例#1
0
def bp_parse(bp, form, session_info):
    """
  Given a JSON representation of a backpack, the user's request form,
  and a copy of the user's session info (steamID, customURL, etc.), returns the following in template_info.

    * A BBCode representation of the backpack
    * A list of status on what parts of the backpack are being displayed
    * Errors if needed.

  """
    schema = get_schema()
    if not schema:
        raise TF2ToolboxException("Could not retrieve the TF2 Item Schema.\n")

    # Load the schema into an usable form, with defindexes as keys.
    s = {}
    for entry in schema['result']['items']:
        used_by_classes = entry.get('used_by_classes', None)
        s[entry['defindex']] = {
            'name':
            entry['item_name'],
            'slot':
            entry.get('item_slot', None),
            'class':
            entry['item_class'],
            'blacklist':
            is_blacklisted(entry),
            'used_by':
            'Multiple' if not used_by_classes or len(used_by_classes) > 1 else
            used_by_classes[0]
        }

    # Load in schema quality mappings: 0 -> "Normal", 1 -> "Genuine"
    s['qualities'] = {}
    for quality in schema['result']['qualities']:
        # TODO: Hacky fix!!!! schema is f*****g up hard.
        if quality not in schema['result']['qualityNames']:
            s['qualities'][schema['result']['qualities']
                           [quality]] = quality.capitalize()
        else:
            s['qualities'][schema['result']['qualities'][quality]] = schema[
                'result']['qualityNames'][quality]

    # Load in schema particle effects
    s['particles'] = {}
    for particle in schema['result'][
            'attribute_controlled_attached_particles']:
        s['particles'][particle['id']] = particle['name']

    # Set up the result schema.
    result = {
        'CATEGORY_ORDER': [
            category for category in tf2toolbox.metadata.BPTEXT_FORM_CATEGORIES
            if category in form
        ],
        'WEAPON_CATEGORIES': [
            'Strange Weapons', 'Genuine Weapons', 'Normal Weapons',
            'Vintage Weapons'
        ]
    }
    for category in tf2toolbox.metadata.BPTEXT_FORM_CATEGORIES:
        result[category] = {}

    # Set up seen class sets for hats and weapons.
    if form['output_sort'] == 'class':
        seen_hat_classes = set()
        seen_weapon_classes = set()

    # Parse each item!
    # The sort_key variables are important for sorting the output.
    # Regular alphabetical sort key: ('Team Captain Untradeable Gifted Team Spirit', 150, 99)
    # (Item w/tags, craftnum, level)
    #
    # Class based sort key for HATS AND WEAPONS: (10, 'Team Captain Untradeable Gifted Pink', 150, 99)
    # The 10 represents Team Captain as a Multiple class item, hence sorting after Scout items (code 1),
    # Soldier items (code 2), etc.
    #
    # We also have special subcategory sort keys for class based sort.
    # The scout one looks like this: (1, 0, 'Scout')
    # This way, it gets sorted ahead of all the Scout weapons/hats (due to the 0).
    for item in bp['result']['items']:

        # Set item info from schema
        item['name'] = s[item['defindex']]['name']
        item['slot'] = s[item['defindex']]['slot']
        item['class'] = s[item['defindex']]['class']
        item['blacklist'] = s[item['defindex']]['blacklist']
        item['used_by'] = s[item['defindex']]['used_by']

        # Get item attributes
        item['attr'] = {}
        if 'attributes' in item:
            for attribute in item['attributes']:
                if attribute['defindex'] == 142:
                    item['attr']['paint'] = int(
                        attribute['float_value'])  # 1.0 -> Team Spirit.
                elif attribute['defindex'] == 186:
                    item['attr']['gifted'] = True
                elif attribute['defindex'] == 229 and (
                        attribute['value'] <= 100
                        or 'display_craft_num' in form):
                    item['attr']['craftnum'] = attribute['value']
                elif attribute['defindex'] == 134 and int(
                        attribute['float_value']):
                    item['attr']['particle'] = s['particles'][int(
                        attribute['float_value'])]

        # Skip invalid items
        if should_skip(item, form):
            continue

        # Hats
        if item['slot'] in ['head', 'misc']:
            quality = s['qualities'][item['quality']]
            # Suffixes: Quality tag, Untradeable, Gifted, Painted, CraftNum, Level if specified

            # Get Unusual particle effect
            if quality == 'Unusual' and 'particle' in item['attr']:
                item['name'] = '%s (%s)' % (item['name'],
                                            item['attr']['particle'])

            sort_key = [item['name']]
            suffix_tags = []

            # Get craft num, level for sort key.
            craft_num = ''
            if 'attr' in item and 'craftnum' in item['attr']:
                sort_key.append(item['attr']['craftnum'])
                craft_num = ' #%d ' % item['attr']['craftnum']

            if 'display_hat_levels' in form:
                sort_key.append(item['level'])
                suffix_tags.append('Level %d' % item['level'])

            if 'flag_cannot_trade' in item:
                sort_key[0] += ' Untradeable'
                suffix_tags.append('Untradeable')

            if 'flag_cannot_craft' in item:
                sort_key[0] += ' Uncraftable'
                suffix_tags.append('Uncraftable')

            if 'gifted' in item['attr']:
                sort_key[0] += ' Gifted'
                suffix_tags.append('Gifted')

            # TODO: Fix dumb array copy hack to get suffix tags correct for plaintext vs bbcode.
            pt_suffix_tags = list(suffix_tags)
            if 'paint' in item['attr']:
                sort_key[0] += ' %s' % tf2toolbox.metadata.PAINT_NUMBER_MAP[
                    'plaintext'][item['attr']['paint']]
                suffix_tags.append(tf2toolbox.metadata.PAINT_NUMBER_MAP[
                    item['attr']['paint']])
                pt_suffix_tags.append(
                    tf2toolbox.metadata.PAINT_NUMBER_MAP['plaintext'][
                        item['attr']['paint']])

            suffix = ' (%s)' % ', '.join(suffix_tags) if suffix_tags else ''
            pt_suffix = ' (%s)' % ', '.join(
                pt_suffix_tags) if pt_suffix_tags else ''

            plaintext_string = '%s%s%s%s' % (
                quality + ' ' if quality != 'Unique' else '', item['name'],
                craft_num, pt_suffix)
            bbcode_string = '%s%s%s[/color]%s' % (
                tf2toolbox.metadata.QUALITY_BBCODE_MAP[quality], item['name'],
                craft_num, suffix)

            if item['name'] in tf2toolbox.metadata.RARE_PROMO_HATS:
                category = 'Rare Promos'
            elif quality != 'Genuine' and item[
                    'name'] in tf2toolbox.metadata.PROMO_HATS:
                category = 'Promo Hats'
            else:
                hat_quality = quality if quality in set(
                    ['Vintage', 'Genuine', 'Unusual']) else 'Normal'
                hat_quality = 'Unusual' if quality in set(
                    ['Community', 'Self-Made', 'Valve']) else hat_quality
                category = '%s Hats' % hat_quality

            # Depending on the output sort, add an extra value to the sort_key.
            if form['output_sort'] == 'class':
                sort_key.insert(
                    0, tf2toolbox.metadata.TF2CLASS_SORT_DICT[item['used_by']])
                # If we haven't seen this class before, add it to seen classes.
                if (category, item['used_by']) not in seen_hat_classes:
                    seen_hat_classes.add((category, item['used_by']))
                    subcat_sort_key = (tf2toolbox.metadata.TF2CLASS_SORT_DICT[
                        item['used_by']], 0, item['used_by'])
                    result[category][subcat_sort_key] = {
                        'SUBCATEGORY': item['used_by']
                    }
            elif form['output_sort'] == 'release':
                pass

            sort_key = tuple(sort_key)
            add_to_result(result,
                          sort_key,
                          category,
                          plaintext=plaintext_string,
                          bbcode=bbcode_string)

        # Weapons
        elif item['slot'] in ['primary', 'secondary', 'melee', 'pda', 'pda2'
                              ] and item['class'] != 'slot_token':
            quality = s['qualities'][item['quality']]
            # Suffixes: Quality tag, Untradeable, Gifted, CraftNum, Weapon Level for Vintage
            # TODO: Support UHHH and other unusual weapons. Should probably go in Genuine Weapons.

            sort_key = [item['name']]
            suffix_tags = []

            # Get craft num, level for sort key.
            craft_num = ''
            if 'attr' in item and 'craftnum' in item['attr']:
                sort_key.append(item['attr']['craftnum'])
                craft_num = ' #%d ' % item['attr']['craftnum']

            if quality == 'Vintage' and (
                    item['level'] not in tf2toolbox.metadata.WEAPON_LEVEL_MAP
                    or item['name'] not in
                    tf2toolbox.metadata.WEAPON_LEVEL_MAP[item['level']]):
                sort_key.append(item['level'])
                suffix_tags.append('Level %d' % item['level'])

            if 'flag_cannot_trade' in item:
                sort_key[0] += ' Untradeable'
                suffix_tags.append('Untradeable')

            if 'flag_cannot_craft' in item:
                sort_key[0] += ' Uncraftable'
                suffix_tags.append('Uncraftable')

            if 'gifted' in item['attr']:
                sort_key[0] += ' Gifted'
                suffix_tags.append('Gifted')

            suffix = ' (%s)' % ', '.join(suffix_tags) if suffix_tags else ''

            plaintext_string = '%s%s%s%s' % (quality + ' '
                                             if quality != 'Unique' else '',
                                             item['name'], craft_num, suffix)
            bbcode_string = '%s%s%s[/color]%s' % (
                tf2toolbox.metadata.QUALITY_BBCODE_MAP[quality], item['name'],
                craft_num, suffix)

            sort_quality = quality
            if quality == 'Unique':
                sort_quality = 'Normal'
            elif quality not in set(['Unique', 'Vintage', 'Strange']):
                sort_quality = 'Genuine'

            category = '%s Weapons' % sort_quality

            # Depending on the output sort, add an extra value to the sort_key.
            if form['output_sort'] == 'class':
                sort_key.insert(
                    0, tf2toolbox.metadata.TF2CLASS_SORT_DICT[item['used_by']])
                # If we haven't seen this class before, add it to seen classes.
                if (category, item['used_by']) not in seen_weapon_classes:
                    seen_weapon_classes.add((category, item['used_by']))
                    subcat_sort_key = (tf2toolbox.metadata.TF2CLASS_SORT_DICT[
                        item['used_by']], 0, item['used_by'])
                    result[category][subcat_sort_key] = {
                        'SUBCATEGORY': item['used_by']
                    }
            elif form['output_sort'] == 'release':
                pass

            sort_key = tuple(sort_key)

            add_to_result(result,
                          sort_key,
                          category,
                          plaintext=plaintext_string,
                          bbcode=bbcode_string)

        # Paint
        elif item['name'] in tf2toolbox.metadata.PAINT_MAP:
            add_to_result(result,
                          item['name'],
                          'Paint',
                          bbcode=tf2toolbox.metadata.PAINT_MAP[item['name']] +
                          '[/color]')

        # Tools
        elif item['class'] in ['tool', 'class_token', 'slot_token'
                               ] or item['slot'] == 'action':
            add_to_result(result, item['name'], 'Tools')

        # Metal
        elif item['class'] == 'craft_item':
            add_to_result(result, item['name'], 'Metal')

        # Crate
        elif item['class'] == 'supply_crate':
            if not 'attributes' in item or item[
                    'name'] != 'Mann Co. Supply Crate':
                add_to_result(result, item['name'], 'Crates')
            else:
                add_to_result(result,
                              int(item['attributes'][0]['float_value']),
                              'Crates',
                              plaintext="Series %d Crate" %
                              int(item['attributes'][0]['float_value']))

    bptext_suffix_tags = []
    if 'display_sc_url' in form:
        bptext_suffix_tags.append(
            'Steam Community URL: http://steamcommunity.com/%s' %
            ('id/' + session_info['customURL'] if 'customURL' in session_info
             else 'profiles/' + session_info['steamID']))

    if form['inc_bp_link'] != 'none':
        if form['inc_bp_link'] == 'tf2b':
            bptext_suffix_tags.append(
                'TF2B: http://tf2b.com/tf2/%s' %
                (session_info['customURL']
                 if 'customURL' in session_info else session_info['steamID']))
        elif form['inc_bp_link'] == 'tf2items':
            bptext_suffix_tags.append(
                'TF2Items: http://tf2items.com/%s' %
                ('id/' + session_info['customURL'] if 'customURL'
                 in session_info else 'profiles/' + session_info['steamID']))
        elif form['inc_bp_link'] == 'optf2':
            bptext_suffix_tags.append(
                'OPTF2: http://optf2.com/user/%s' %
                (session_info['customURL']
                 if 'customURL' in session_info else session_info['steamID']))

    # TODO: Fix icky hack here to append extra line for Reddit
    if form['output_type'] == 'markdown':
        bptext_suffix_tags = [tag + '\n' for tag in bptext_suffix_tags]

    return bp_to_text(
        result, 'display_credit' in form, 'only_dup_weps' in form,
        form['output_type']) + '\n' + '\n'.join(bptext_suffix_tags)
示例#2
0
def bp_parse(bp, form, session_info):
    """
    Given a JSON representation of a backpack, the user's request form,
    and a copy of the user's session info (steamID, customURL, etc.), returns the following in template_info.

        * A BBCode representation of the backpack
        * A list of status on what parts of the backpack are being displayed
        * Errors if needed.

    """
    schema = get_schema()
    if not schema:
        raise TF2ToolboxException("Could not retrieve the TF2 Item Schema.\n")


    # Load the schema into an usable form, with defindexes as keys.
    s = {}
    for entry in schema['result']['items']:
        used_by_classes = entry.get('used_by_classes', None)
        s[entry['defindex']] = {'name': entry['item_name'],
                                'slot': entry.get('item_slot', None),
                                'class': entry['item_class'],
                                'blacklist': is_blacklisted(entry),
                                'used_by': 'Multiple' if not used_by_classes or len(used_by_classes) > 1 else used_by_classes[0]
                                }

    # Load in schema quality mappings: 0 -> "Normal", 1 -> "Genuine"
    s['qualities'] = {}
    for quality in schema['result']['qualities']:
        # TODO: Hacky fix!!!! schema is f*****g up hard.
        if quality not in schema['result']['qualityNames']:
            s['qualities'][schema['result']['qualities'][quality]] = quality.capitalize()
        else:
            s['qualities'][schema['result']['qualities'][quality]] = schema['result']['qualityNames'][quality]

    # Load in schema particle effects
    s['particles'] = {}
    for particle in schema['result']['attribute_controlled_attached_particles']:
        s['particles'][particle['id']] = particle['name']

    # Set up the result schema.
    result = {
        'CATEGORY_ORDER': [category for category in tf2toolbox.metadata.BPTEXT_FORM_CATEGORIES if category in form],
        'WEAPON_CATEGORIES': ['Strange Weapons', 'Genuine Weapons', 'Normal Weapons', 'Vintage Weapons']
    }
    for category in tf2toolbox.metadata.BPTEXT_FORM_CATEGORIES:
        result[category] = {}

    # Set up seen class sets for hats and weapons.
    if form['output_sort'] == 'class':
        seen_hat_classes = set()
        seen_weapon_classes = set()

    # Parse each item!
    # The sort_key variables are important for sorting the output.
    # Regular alphabetical sort key: ('Team Captain Untradeable Gifted Team Spirit', 150, 99)
    # (Item w/tags, craftnum, level)
    #
    # Class based sort key for HATS AND WEAPONS: (10, 'Team Captain Untradeable Gifted Pink', 150, 99)
    # The 10 represents Team Captain as a Multiple class item, hence sorting after Scout items (code 1),
    # Soldier items (code 2), etc.
    #
    # We also have special subcategory sort keys for class based sort.
    # The scout one looks like this: (1, 0, 'Scout')
    # This way, it gets sorted ahead of all the Scout weapons/hats (due to the 0).
    for item in bp['result']['items']:

        # Set item info from schema
        item['name'] = s[item['defindex']]['name']
        item['slot'] = s[item['defindex']]['slot']
        item['class'] = s[item['defindex']]['class']
        item['blacklist'] = s[item['defindex']]['blacklist']
        item['used_by'] = s[item['defindex']]['used_by']

        # Get item attributes
        item['attr'] = {}
        if 'attributes' in item:
            for attribute in item['attributes']:
                if attribute['defindex'] == 142:
                    item['attr']['paint'] = int(attribute['float_value']) # 1.0 -> Team Spirit.
                elif attribute['defindex'] == 186:
                    item['attr']['gifted'] = True
                elif attribute['defindex'] == 229 and (attribute['value'] <= 100 or 'display_craft_num' in form):
                    item['attr']['craftnum'] = attribute['value']
                elif attribute['defindex'] == 134 and int(attribute['float_value']):
                    item['attr']['particle'] = s['particles'][int(attribute['float_value'])]

        # Skip invalid items
        if should_skip(item, form):
            continue

        # Hats
        if item['slot'] in ['head', 'misc']:
            quality = s['qualities'][item['quality']]
            # Suffixes: Quality tag, Untradeable, Gifted, Painted, CraftNum, Level if specified

            # Get Unusual particle effect
            if quality == 'Unusual' and 'particle' in item['attr']:
                item['name'] = '%s (%s)' % (item['name'], item['attr']['particle'])

            sort_key = [item['name']]
            suffix_tags = []

            # Get craft num, level for sort key.
            craft_num = ''
            if 'attr' in item and 'craftnum' in item['attr']:
                sort_key.append(item['attr']['craftnum'])
                craft_num = ' #%d ' % item['attr']['craftnum']

            if 'display_hat_levels' in form:
                sort_key.append(item['level'])
                suffix_tags.append('Level %d' % item['level'])

            if 'flag_cannot_trade' in item:
                sort_key[0] += ' Untradeable'
                suffix_tags.append('Untradeable')

            if 'flag_cannot_craft' in item:
                sort_key[0] += ' Uncraftable'
                suffix_tags.append('Uncraftable')

            if 'gifted' in item['attr']:
                sort_key[0] += ' Gifted'
                suffix_tags.append('Gifted')

            # TODO: Fix dumb array copy hack to get suffix tags correct for plaintext vs bbcode.
            pt_suffix_tags = list(suffix_tags)
            if 'paint' in item['attr']:
                sort_key[0] += ' %s' % tf2toolbox.metadata.PAINT_NUMBER_MAP['plaintext'][item['attr']['paint']]
                suffix_tags.append(tf2toolbox.metadata.PAINT_NUMBER_MAP[item['attr']['paint']])
                pt_suffix_tags.append(tf2toolbox.metadata.PAINT_NUMBER_MAP['plaintext'][item['attr']['paint']])

            suffix = ' (%s)' % ', '.join(suffix_tags) if suffix_tags else ''
            pt_suffix = ' (%s)' % ', '.join(pt_suffix_tags) if pt_suffix_tags else ''

            plaintext_string = '%s%s%s%s' % (quality+' ' if quality != 'Unique' else '', item['name'], craft_num, pt_suffix)
            bbcode_string = '%s%s%s[/color]%s' % (tf2toolbox.metadata.QUALITY_BBCODE_MAP[quality], item['name'], craft_num, suffix)

            if item['name'] in tf2toolbox.metadata.RARE_PROMO_HATS:
                category = 'Rare Promos'
            elif quality != 'Genuine' and item['name'] in tf2toolbox.metadata.PROMO_HATS:
                category = 'Promo Hats'
            else:
                hat_quality = quality if quality in set(['Vintage', 'Genuine', 'Unusual']) else 'Normal'
                hat_quality = 'Unusual' if quality in set(['Community', 'Self-Made', 'Valve']) else hat_quality
                category = '%s Hats' % hat_quality

            # Depending on the output sort, add an extra value to the sort_key.
            if form['output_sort'] == 'class':
                sort_key.insert(0, tf2toolbox.metadata.TF2CLASS_SORT_DICT[item['used_by']])
                # If we haven't seen this class before, add it to seen classes.
                if (category, item['used_by']) not in seen_hat_classes:
                    seen_hat_classes.add((category, item['used_by']))
                    subcat_sort_key = (tf2toolbox.metadata.TF2CLASS_SORT_DICT[item['used_by']], 0, item['used_by'])
                    result[category][subcat_sort_key] = {'SUBCATEGORY': item['used_by']}
            elif form['output_sort'] == 'release':
                pass

            sort_key = tuple(sort_key)
            add_to_result(result, sort_key, category, plaintext=plaintext_string, bbcode=bbcode_string)



        # Weapons
        elif item['slot'] in ['primary', 'secondary', 'melee', 'pda', 'pda2', 'building'] and item['class'] != 'slot_token':
            quality = s['qualities'][item['quality']]
            # Suffixes: Quality tag, Untradeable, Gifted, CraftNum, Weapon Level for Vintage
            # TODO: Support UHHH and other unusual weapons. Should probably go in Genuine Weapons.

            sort_key = [item['name']]
            suffix_tags = []

            # Get craft num, level for sort key.
            craft_num = ''
            if 'attr' in item and 'craftnum' in item['attr']:
                sort_key.append(item['attr']['craftnum'])
                craft_num = ' #%d ' % item['attr']['craftnum']

            if quality == 'Vintage' and (item['level'] not in tf2toolbox.metadata.WEAPON_LEVEL_MAP or item['name'] not in tf2toolbox.metadata.WEAPON_LEVEL_MAP[item['level']]):
                sort_key.append(item['level'])
                suffix_tags.append('Level %d' % item['level'])

            if 'flag_cannot_trade' in item:
                sort_key[0] += ' Untradeable'
                suffix_tags.append('Untradeable')

            if 'flag_cannot_craft' in item:
                sort_key[0] += ' Uncraftable'
                suffix_tags.append('Uncraftable')

            if 'gifted' in item['attr']:
                sort_key[0] += ' Gifted'
                suffix_tags.append('Gifted')

            suffix = ' (%s)' % ', '.join(suffix_tags) if suffix_tags else ''

            plaintext_string = '%s%s%s%s' % (quality+' ' if quality != 'Unique' else '', item['name'], craft_num, suffix)
            bbcode_string = '%s%s%s[/color]%s' % (tf2toolbox.metadata.QUALITY_BBCODE_MAP[quality], item['name'], craft_num, suffix)

            sort_quality = quality
            if quality == 'Unique':
                sort_quality = 'Normal'
            elif quality not in set(['Unique', 'Vintage', 'Strange']):
                sort_quality = 'Genuine'

            category = '%s Weapons' % sort_quality

            # Depending on the output sort, add an extra value to the sort_key.
            if form['output_sort'] == 'class':
                sort_key.insert(0, tf2toolbox.metadata.TF2CLASS_SORT_DICT[item['used_by']])
                # If we haven't seen this class before, add it to seen classes.
                if (category, item['used_by']) not in seen_weapon_classes:
                    seen_weapon_classes.add((category, item['used_by']))
                    subcat_sort_key = (tf2toolbox.metadata.TF2CLASS_SORT_DICT[item['used_by']], 0, item['used_by'])
                    result[category][subcat_sort_key] = {'SUBCATEGORY': item['used_by']}
            elif form['output_sort'] == 'release':
                pass

            sort_key = tuple(sort_key)

            add_to_result(result, sort_key, category, plaintext=plaintext_string, bbcode=bbcode_string)

        # Paint
        elif item['name'] in tf2toolbox.metadata.PAINT_MAP:
            add_to_result(result, item['name'], 'Paint', bbcode=tf2toolbox.metadata.PAINT_MAP[item['name']]+'[/color]')

        # Tools
        elif item['class'] in ['tool', 'class_token', 'slot_token'] or item['slot'] == 'action':
            add_to_result(result, item['name'], 'Tools')

        # Metal
        elif item['class'] == 'craft_item':
            add_to_result(result, item['name'], 'Metal')

        # Crate
        elif item['class'] == 'supply_crate':
            if not 'attributes' in item or item['name'] != 'Mann Co. Supply Crate':
                add_to_result(result, item['name'], 'Crates')
            else:
                add_to_result(result, int(item['attributes'][0]['float_value']), 'Crates', plaintext="Series %d Crate" % int(item['attributes'][0]['float_value']))

    bptext_suffix_tags = []
    if 'display_sc_url' in form:
        bptext_suffix_tags.append('Steam Community URL: http://steamcommunity.com/%s' % ('id/'+session_info['customURL'] if 'customURL' in session_info else 'profiles/'+session_info['steamID']))

    if form['inc_bp_link'] != 'none':
        if form['inc_bp_link'] == 'tf2b':
            bptext_suffix_tags.append('TF2B: http://tf2b.com/tf2/%s' % (session_info['customURL'] if 'customURL' in session_info else session_info['steamID']))
        elif form['inc_bp_link'] == 'tf2items':
            bptext_suffix_tags.append('TF2Items: http://tf2items.com/%s' % ('id/'+session_info['customURL'] if 'customURL' in session_info else 'profiles/'+session_info['steamID']))
        elif form['inc_bp_link'] == 'optf2':
            bptext_suffix_tags.append('OPTF2: http://optf2.com/user/%s' % (session_info['customURL'] if 'customURL' in session_info else session_info['steamID']))

    # TODO: Fix icky hack here to append extra line for Reddit
    if form['output_type'] == 'markdown':
        bptext_suffix_tags = [tag+'\n' for tag in bptext_suffix_tags]

    return bp_to_text(result, 'display_credit' in form, 'only_dup_weps' in form, form['output_type']) + '\n' + '\n'.join(bptext_suffix_tags)
示例#3
0
def bp_metal(bp, form):
    """
    Given a JSON representation of a backpack, the user's request form,
    and a copy of the user's session info (steamID, customURL, etc.),
    returns a Python result dict to be rendered by the template.

    result = {
        'ordered_classes': ['Scout', 'Soldier', 'Pyro', 'Demoman', 'Heavy', 'Engineer', 'Medic', 'Sniper', 'Spy', 'Multiple'],
        'weapons': {},
        'v_all_count': 0,
        'nv_all_count': 0,
        'v_primary_count': 0,
        'nv_primary_count': 0,
        'v_secondary_count': 0,
        'nv_secondary_count': 0,
    }


    """
    schema = get_schema()
    if not schema:
        raise TF2ToolboxException("Could not retrieve the TF2 Item Schema.\n")

    # Load the schema into an usable form, with defindexes as keys.
    s = {}
    for entry in schema['result']['items']:
        s[entry['defindex']] = {'name': entry['item_name'],
                                'slot': entry.get('item_slot', None),
                                'class': entry['item_class'],
                                'craft': entry.get('craft_material_type', None),
                                'image': entry['image_url'],
                                'used_by': entry.get('used_by_classes', None)
                               }

    # Load in schema quality mappings: 0 -> "Normal", 1 -> "Genuine"
    s['qualities'] = {}
    for quality in schema['result']['qualities']:
        # TODO: Hacky fix!!!! schema is f*****g up hard.
        if quality not in schema['result']['qualityNames']:
            s['qualities'][schema['result']['qualities'][quality]] = quality.capitalize()
        else:
            s['qualities'][schema['result']['qualities'][quality]] = schema['result']['qualityNames'][quality]


    # Set up the result schema.
    result = {
        'ordered_classes': ['Scout', 'Soldier', 'Pyro', 'Demoman', 'Heavy', 'Engineer', 'Medic', 'Sniper', 'Spy', 'Multiple'],
        'weapons': {},
        'v_all_count': 0,
        'nv_all_count': 0,
        'v_primary_count': 0,
        'nv_primary_count': 0,
        'v_secondary_count': 0,
        'nv_secondary_count': 0,
    }
    for cls in result['ordered_classes']:
        result['weapons'][cls] = {'standard': {}, 'special': [], 'total_s_count': 0, 'total_v_count': 0, 'total_nv_count': 0} # standard -> 'Item Name' {picture, nv_count, v_count}. special -> (picURL, altText)

    # Parse each item!
    for item in bp['result']['items']:

        # Skip invalid pages
        if 'all' not in form.getlist('pages[]'):
            pages = [int(page) for page in form.getlist('pages[]')]
            inv_page = ((item['inventory'] & 0xFFFF) - 1) / 50 + 1
            if inv_page not in pages:
                continue

        # Set item info from schema
        item['craft'] = s[item['defindex']]['craft']

        # If the item is a craftable weapon, count it!
        if item['craft'] == 'weapon':
            item['slot'] = s[item['defindex']]['slot']
            item['name'] = s[item['defindex']]['name']
            item['class'] = s[item['defindex']]['class']
            item['used_by'] = s[item['defindex']]['used_by']
            item['image'] = s[item['defindex']]['image']
            quality = s['qualities'][item['quality']]

            # Log item slot and count.
            if quality == 'Vintage':
                result['v_all_count'] += 1
            elif quality == 'Unique':
                result['nv_all_count'] += 1

            if item['slot'] in ['primary', 'secondary']:
                if quality == 'Vintage':
                    result['v_' + item['slot'] + '_count'] += 1
                elif quality == 'Unique':
                    result['nv_' + item['slot'] + '_count'] += 1

            # Figure out which TF2 class the item goes in
            if not item['used_by']:
                print '[WTF] Item not used by any class? %s' % item['name']
            elif len(item['used_by']) > 1:
                use_class = 'Multiple'
            elif len(item['used_by']) == 1:
                use_class = item['used_by'][0]

            # Classify the item.
            # Special weapons are any quality besides Unique/Vintage, or Vintage Offlevel, Named, or Described.
            if quality not in ['Unique', 'Vintage'] or (quality == 'Vintage' and (item['level'] not in WEAPON_LEVEL_MAP or item['name'] not in WEAPON_LEVEL_MAP[item['level']])) or 'custom_name' in item or 'custom_desc' in item:
                suffix_tags = []
                if 'custom_name' in item:
                    display_name = item['custom_name']
                    suffix_tags.append('%s%s' % (quality+' ' if quality != 'Unique' else '', item['name']))
                else:
                    display_name = '%s%s' % (quality+' ' if quality != 'Unique' else '', item['name'])

                if quality == 'Vintage' and (item['level'] not in WEAPON_LEVEL_MAP or item['name'] not in WEAPON_LEVEL_MAP[item['level']]):
                    suffix_tags.append('Level %d' % item['level'])

                if 'custom_desc' in item:
                    suffix_tags.append('Description: %s' % item['custom_desc'])

                suffix = (' (%s)' % ', '.join(suffix_tags)) if suffix_tags else ''

                result['weapons'][use_class]['special'].append(('%s%s' % (display_name, suffix), item['image']))
                result['weapons'][use_class]['total_s_count'] += 1

            # Non special items just get entered.
            else:
                if item['name'] not in result['weapons'][use_class]['standard']:
                    result['weapons'][use_class]['standard'][item['name']] = \
                        {'image': item['image'],
                         'v_count': 1 if quality == 'Vintage' else 0,
                         'nv_count': 1 if quality == 'Unique' else 0
                        }
                else:
                    if quality == 'Vintage':
                        result['weapons'][use_class]['standard'][item['name']]['v_count'] += 1
                    elif quality == 'Unique':
                        result['weapons'][use_class]['standard'][item['name']]['nv_count'] += 1
                if quality == 'Vintage':
                    result['weapons'][use_class]['total_v_count'] += 1
                elif quality == 'Unique':
                    result['weapons'][use_class]['total_nv_count'] += 1

    return result
示例#4
0
def bp_weapons(bp, session_info):
  """
  Given a JSON representation of a backpack,  and a copy of the user's session info (steamID, customURL, etc.),
  returns the following in template_info.

    * Weapon info on the backpack
    * Errors if needed.

  """

  # Result schema;
  """
  'result': {
    'Scout': {
      'essential': {'Sandman': True, 'Soda Popper': False}
      'alternative': {'Three-Rune Blade': False}
    }
    'Soldier'...
    'Multiple'
  }
  """
  schema = get_schema()
  if not schema:
    raise TF2ToolboxException("Could not retrieve the TF2 Item Schema.\n")

  result = {
    'ordered_classes': ['Scout', 'Soldier', 'Pyro', 'Demoman', 'Heavy', 'Engineer', 'Medic', 'Sniper', 'Spy', 'Multiple'],
    'Special': {'alternative': {}}
  }
  for cls in result['ordered_classes']:
    result[cls] = {'essential': {}, 'alternative': {}}

  # Load the schema into an usable form, with defindexes as keys.
  s = {}
  for entry in schema['result']['items']:
    # Load the weapon list.
    if entry.get('item_slot', None) in ['primary', 'secondary', 'melee', 'pda', 'pda2'] and entry['item_class'] != 'slot_token':

      # Skip multiclass stock upgradeables.
      if entry.get('defindex') >= 190 and entry.get('defindex') <= 212:
        continue
      used_by = entry.get('used_by_classes', None)
      item_name = entry['item_name']

      # Categorize the weapon. Is it essential (adds new functionality to game?) or alternative (replicates existing functionality/promotional)
      # Is it used by one class or multiple?
      # Is it a stock weapon? (defindex 0-30). If so, initialize to True.
      category = 'essential'
      if item_name in ALT_WEAPONS or item_name in LIMITED_WEAPONS:
        category = 'alternative'

      if not used_by or len(used_by) > 1: # Special case for Saxxy - used_by = None
        cls = 'Multiple'
      else:
        cls = used_by[0]

      if item_name not in result[cls][category]:
        if entry.get('defindex') <= 30:
          result[cls][category][item_name] = [True, entry.get('image_url')]
        else:
          result[cls][category][item_name] = [False, entry.get('image_url')]

      s[entry['defindex']] = {'name': entry['item_name'],
                              'used_by': cls,
                              'category': category
                             }

  # Parse each item!
  for item in bp['result']['items']:
    # Skip non-indexed weapons.
    if item['defindex'] not in s:
      continue

    cls = s[item['defindex']]['used_by']
    category = s[item['defindex']]['category']
    name = s[item['defindex']]['name']

    result[cls][category][name][0] = True

  return result