Exemplo n.º 1
0
def ResolveRuleForObject(object, rule):
    from SFIWikiBotLib import ItemUtils
    from SFIWikiBotLib import ShipUtils

    value1 = None
    if rule['id'] in object:
        value1 = NormalizeString(object[rule['id']])
    elif rule['id'] == 'ItemUtils.IsBeamWeapon':
        value1 = ItemUtils.IsBeamWeapon(object)
    elif rule['id'] == 'ItemUtils.IsItemHidden':
        value1 = ItemUtils.IsItemHidden(object)
    elif rule['id'] == 'ItemUtils.IsItemNprExclusive':
        value1 = ItemUtils.IsItemNprExclusive(object)
    elif rule['id'] == 'ItemUtils.GetItemRange':
        value1 = ItemUtils.GetItemRange(object)
    elif rule['id'] == 'ItemUtils.GetItemDps':
        value1 = ItemUtils.GetItemDps(object)
    elif rule['id'] == 'ItemUtils.GetItemDpsIncludingEffectDamage':
        value1 = ItemUtils.GetItemDpsIncludingEffectDamage(object)
    elif rule['id'] == 'ItemUtils.GetItemDpe':
        value1 = ItemUtils.GetItemDpe(object)
    elif rule['id'] == 'ItemUtils.GetItemDpeIncludingEffectDamage':
        value1 = ItemUtils.GetItemDpeIncludingEffectDamage(object)
    elif rule['id'] == 'ItemUtils.GetWeaponEffectName':
        v = ItemUtils.GetWeaponEffectName(object)
        value1 = NormalizeString(v if v else "None")
    elif rule['id'] == 'ItemUtils.GetShieldEffectName':
        v = ItemUtils.GetShieldEffectName(object)
        value1 = NormalizeString(v if v else "None")
    elif rule['id'] == 'ItemUtils.GetItemEffectTime':
        value1 = ItemUtils.GetItemEffectTime(object)
    elif rule['id'] == 'ItemUtils.GetItemSource':
        value1 = NormalizeString(ItemUtils.GetItemSource(object))
    elif rule['id'] == 'ItemUtils.GetItemSkillName':
        value1 = NormalizeString(ItemUtils.GetItemSkillName(object))
    elif rule['id'] == 'ItemUtils.GetItemAugType':
        value1 = NormalizeString(ItemUtils.GetItemAugType(object))
    elif rule['id'] == 'ItemUtils.GetItemSkillLevel':
        value1 = ItemUtils.GetItemSkillLevel(object)
    elif rule['id'] == 'ItemUtils.GetItemDamageType':
        value1 = NormalizeString(ItemUtils.GetItemDamageType(object) or '')
    elif rule['id'] == 'ItemUtils.GetItemDescription':
        value1 = NormalizeString(ItemUtils.GetItemDescription(object))
    elif rule['id'] == 'ItemUtils.ItemDisplayStatBPLocation':
        value1 = NormalizeString(ItemUtils.ItemDisplayStatBPLocation(object))
    elif rule['id'] == 'ItemUtils.GetItemPurchasePrice':
        value1 = ItemUtils.GetItemPurchasePrice(object)
    elif rule['id'] == 'ShipUtils.GetShipPurchasePrice':
        value1 = ShipUtils.GetShipPurchasePrice(object)
    elif rule['id'] == 'ShipUtils.GetMaxSpeedForShip':
        value1 = ShipUtils.GetMaxSpeedForShip(object)
    elif rule['id'] == 'ShipUtils.ShipCanBeBoughtByPlayers':
        value1 = ShipUtils.ShipCanBeBoughtByPlayers(object)
    elif rule['id'] == 'ShipUtils.GetTypeForShip':
        value1 = NormalizeString(ShipUtils.GetTypeForShip(object))
    elif rule['id'] == 'ShipUtils.IsShipHidden':
        value1 = ShipUtils.IsShipHidden(object)
    elif rule['id'] == 'ShipUtils.GetRaceForShip':
        value1 = NormalizeString(ShipUtils.GetRaceForShip(object))
    elif rule['id'] == 'ItemUtils.GetRaceForItem':
        value1 = NormalizeString(ItemUtils.GetRaceForItem(object))
    elif rule['id'] == 'ItemUtils.GetItemTotalDamagePerVolley':
        value1 = ItemUtils.GetItemTotalDamagePerVolley(object)

    if 'degrees.' in rule['id'].lower() and value1 is None:
        prop = rule['id'].split('.', 1)[1]
        if prop in object:
            value1 = object[prop] * 30

    if 'percent.' in rule['id'].lower() and value1 is None:
        prop = rule['id'].split('.', 1)[1]
        if prop in object:
            value1 = object[prop] * 100

    value2 = NormalizeString(rule['value'])

    func = switcher.get(rule['operator'], (lambda v1, v2: None))
    try:
        rtnVal = func(value1, value2)
    except:
        rtnVal = False

    return rtnVal
Exemplo n.º 2
0
def AddWikiLinksToText(input,
                       useHtml=False,
                       allowExtraWeaponCheck=True,
                       additionalReplacementOverrides=None):
    from SFIWikiBotLib import WikiUtils
    from SFIWikiBotLib import Config
    from SFIWikiBotLib import ItemUtils

    includeStemming = True
    lowercaseReplacementExactMatchList = [
        v.lower().replace('_', ' ')
        for v in Config.wikiLinkReplacementExactMatchRequiredList
    ]
    normalizedReplacementExclusionList = [
        NormalizeString(v, includeStemming)
        for v in Config.wikiLinkReplacementExclusionList
    ]
    # normalizedReplacementOverrideList = { NormalizeString(k, includeStemming):NormalizeString(v, includeStemming) for k, v in Config.wikiLinkReplacementOverrideList.items() }
    normalizedReplacementOverrideList = {}
    if type(additionalReplacementOverrides) == dict:
        for k, v in additionalReplacementOverrides.items():
            if not v:
                normalizedReplacementExclusionList.append(
                    NormalizeString(k, includeStemming))
            else:
                normalizedReplacementOverrideList[NormalizeString(
                    k, includeStemming)] = NormalizeString(v, includeStemming)

    lowercaseNonStemmedReplacementOverrideList = {
        k.lower().replace('_', ' '): v.lower().replace('_', ' ')
        for k, v in Config.wikiLinkReplacementOverrideList.items()
    }

    phraseList = SplitTextIntoPhrases(input,
                                      Config.maxWordsInArticleTitleSearch)
    replacementList = []
    replacementInfo = {}
    placeholderCount = 0

    for origPhrase in phraseList:
        normalizedPhrase = origPhrase.lower().replace('_', ' ')
        for s, r in lowercaseNonStemmedReplacementOverrideList.items():
            normalizedPhrase = normalizedPhrase.replace(s, r)

        if normalizedPhrase not in lowercaseReplacementExactMatchList:
            normalizedPhraseTmp = NormalizeString(normalizedPhrase,
                                                  includeStemming)
            if normalizedPhraseTmp not in lowercaseReplacementExactMatchList:
                normalizedPhrase = normalizedPhraseTmp

        if normalizedPhrase in normalizedReplacementExclusionList:
            continue
        if normalizedPhrase in normalizedReplacementOverrideList:
            normalizedPhrase = normalizedReplacementOverrideList[
                normalizedPhrase]

        nameList = [origPhrase]
        if normalizedPhrase not in nameList:
            nameList.append(normalizedPhrase)

        if allowExtraWeaponCheck:
            altNameInfo = ItemUtils.SplitNameIntoBaseNameAndItemLevel(
                origPhrase)
            altNameLower = altNameInfo['fullNameMinusLevel'].lower().replace(
                '_', ' ')
            if altNameLower != origPhrase.lower().replace('_', ' '):
                if altNameLower in ItemUtils.itemBaseNameList:
                    altName = NormalizeString(
                        altNameInfo['fullNameMinusLevel'], includeStemming)
                    if altName not in normalizedReplacementExclusionList:
                        nameList.append(altNameInfo['fullNameMinusLevel'])

        wikiPage = WikiUtils.GetWikiArticlePageForNameList(nameList)
        if wikiPage:
            replacementInfo = {}
            replacementInfo["originalText"] = origPhrase
            if useHtml:
                replacementInfo[
                    "replacementText"] = '<a href="{}" target="_blank">{}</a>'.format(
                        WikiUtils.GetWikiLink(wikiPage), origPhrase)
            else:
                replacementInfo["replacementText"] = WikiUtils.GetWikiTextLink(
                    wikiPage, origPhrase)
            replacementInfo["placeholder"] = "~~placeholder:{}:~~".format(
                placeholderCount)
            replacementList.append(replacementInfo)

            placeholderCount += 1
            input = re.sub(
                r'\b{}\b'.format(re.escape(replacementInfo["originalText"])),
                replacementInfo["placeholder"], input, 0, re.I)

    for replacementInfo in replacementList:
        input = re.sub(re.escape(replacementInfo["placeholder"]),
                       replacementInfo["replacementText"], input, 0, re.I)

    return input
Exemplo n.º 3
0
def GetItemList(params, bodyData):
    wikiTableOutput = ""
    htmlTableOutput = ""
    filteredItemList = []

    tableHeader = ""
    tableCaption = ""
    tableClassNames = ""
    tableColumnList = []

    ruleSet = json.loads(bodyData)
    filteredItemList = GeneralUtils.SearchObjectListUsingRuleset(
        ItemUtils.itemData, ruleSet)
    filteredItemList = sorted(filteredItemList, key=lambda v: v['name'])

    tableId = GeneralUtils.GenerateDataSignature(ruleSet)

    if 'useCustomTableOptions' in params and params['useCustomTableOptions'][
            0] == '1':
        if 'tableHeader' in params:
            tableHeader = params["tableHeader"][0]
        if 'tableCaption' in params:
            tableCaption = params["tableCaption"][0]
        if 'tableClassNames' in params:
            tableClassNames = params["tableClassNames"][0]
        if 'tableColumnList[]' in params:
            tableColumnList = params["tableColumnList[]"]
        elif 'tableColumnList' in params:
            tableColumnList = params["tableColumnList"][0]

        if tableColumnList:
            tableData = ItemUtils.GetWikiDisplayDataForItemList(
                filteredItemList, tableColumnList)
            dataSignature = GeneralUtils.GenerateDataSignature(tableData)
            tableClassNames += " data-{} generated-{}".format(
                dataSignature,
                date.today().isoformat())
            tableClassNames = tableClassNames.strip()
            wikiTableOutput = WikiUtils.ConvertListToWikiTable(
                tableData, tableHeader, tableCaption, tableClassNames, tableId)

            tableData = ItemUtils.GetDisplayDataForItemList(
                filteredItemList, tableColumnList)
            htmlTableOutput = GeneralUtils.ConvertListToHtmlTable(
                tableData, tableHeader, tableCaption, tableClassNames, tableId)
        else:
            htmlTableOutput = "No table columns specified - Unable to display data"
            wikiTableOutput = "No table columns specified - Unable to display data"

    else:
        itemTypeList = [2, 3, 4, 5, 6, 14, 1]
        weaponTypeList = [1, 2, 3, 4, 5]

        for itemType in itemTypeList:
            if itemType == 3:
                for weaponType in weaponTypeList:
                    itemList = []
                    try:
                        itemList = [
                            item for item in filteredItemList
                            if 'type' in item and item['type'] == itemType
                            and 'weaponType' in item
                            and item['weaponType'] == weaponType
                        ]
                    except:
                        pass

                    if itemList:
                        tableInfo = ItemUtils.GetDefaultTableInfoByItemType(
                            itemType, weaponType)
                        tableHeader = tableInfo['tableHeader']
                        tableCaption = tableInfo['tableCaption']
                        tableColumnList = tableInfo['tableColumnList']
                        tableColumnTitleList = tableInfo[
                            'tableColumnTitleList']
                        tableClassNames = tableInfo['tableClassNames']
                        if len(itemList) > 7:
                            tableClassNames += " floatheader"
                            tableClassNames = tableClassNames.strip()

                        tableData = ItemUtils.GetWikiDisplayDataForItemList(
                            itemList, tableColumnList)
                        dataSignature = GeneralUtils.GenerateDataSignature(
                            tableData)
                        tableClassNames += " data-{} generated-{}".format(
                            dataSignature,
                            date.today().isoformat())
                        tableClassNames = tableClassNames.strip()
                        wikiTableOutput += WikiUtils.ConvertListToWikiTable(
                            tableData, tableHeader, tableCaption,
                            tableClassNames, tableId, tableColumnTitleList)

                        tableData = ItemUtils.GetDisplayDataForItemList(
                            itemList, tableColumnList)
                        htmlTableOutput += GeneralUtils.ConvertListToHtmlTable(
                            tableData, tableHeader, tableCaption,
                            tableClassNames, tableId, tableColumnTitleList)
            else:
                itemList = []
                try:
                    itemList = [
                        item for item in filteredItemList
                        if 'type' in item and item['type'] == itemType
                    ]
                except:
                    pass

                if itemList:
                    tableInfo = ItemUtils.GetDefaultTableInfoByItemType(
                        itemType)
                    tableHeader = tableInfo['tableHeader']
                    tableCaption = tableInfo['tableCaption']
                    tableColumnList = tableInfo['tableColumnList']
                    tableColumnTitleList = tableInfo['tableColumnTitleList']
                    tableClassNames = tableInfo['tableClassNames']
                    if len(itemList) > 7:
                        tableClassNames += " floatheader"
                        tableClassNames = tableClassNames.strip()

                    tableData = ItemUtils.GetWikiDisplayDataForItemList(
                        itemList, tableColumnList)
                    dataSignature = GeneralUtils.GenerateDataSignature(
                        tableData)
                    tableClassNames += " data-{} generated-{}".format(
                        dataSignature,
                        date.today().isoformat())
                    tableClassNames = tableClassNames.strip()
                    wikiTableOutput += WikiUtils.ConvertListToWikiTable(
                        tableData, tableHeader, tableCaption, tableClassNames,
                        tableId, tableColumnTitleList)

                    tableData = ItemUtils.GetDisplayDataForItemList(
                        itemList, tableColumnList)
                    htmlTableOutput += GeneralUtils.ConvertListToHtmlTable(
                        tableData, tableHeader, tableCaption, tableClassNames,
                        tableId, tableColumnTitleList)

    js = '$("#resultDisplayHtmlTable").html({});\n'.format(
        json.dumps(htmlTableOutput))
    js += '$("#resultDisplayWiki").html({});\n'.format(
        json.dumps(html.escape(wikiTableOutput)))
    js += '$("#resultDisplayJson").html(\'{}\');\n'.format(
        html.escape(json.dumps(filteredItemList, indent=2,
                               sort_keys=True)).replace('\n', '\\n').replace(
                                   "'", "\\'"))
    js += '$("#resultCount").html(\'{}\');\n'.format(len(filteredItemList))
    js += 'finderLastResult = {};\n'.format(
        json.dumps(filteredItemList, sort_keys=True))
    js += 'console.log("finderLastResult:", finderLastResult);\n'
    return js
    print(
        "Not logged in. Please check that your username ({}) and password ({}) are correct."
        .format(Config.botUsername, '*' * len(Config.botPassword)))
    exit(1)

comment = None

# Make sure we're working with fresh data
print('** Refreshing all cache',
      datetime.now(tz).strftime("%I:%M %p").lstrip('0'))
WikiUtils.RefreshWikiImageCache()
WikiUtils.RefreshWikiPageCache()
DataLoader.RefreshPublicData()
DataLoader.RefreshPrivateData()
SmallConstants.Initialize()
ItemUtils.Initialize()
ShipUtils.Initialize()
GalaxyUtils.Initialize()
WikiUtils.Initialize()
time.sleep(Config.pauseBetweenContentUpdateStepsInSec)

print('** Update/add planet pages',
      datetime.now(tz).strftime("%I:%M %p").lstrip('0'))
WikiUtils.UpdateIndividualPagesForAllPlanets(comment)
time.sleep(Config.pauseBetweenContentUpdateStepsInSec)

print('** Update star system pages',
      datetime.now(tz).strftime("%I:%M %p").lstrip('0'))
WikiUtils.UpdateStarSystemPages(comment)

print('** Update lore page', datetime.now(tz).strftime("%I:%M %p").lstrip('0'))
Exemplo n.º 5
0
def application(environ, start_response):
    response = '404 Not Found'
    responseBody = ""
    responseContentType = 'text/html'
    result = None
    headerList = []

    path = environ['PATH_INFO']
    queryString = parse_qs(environ['QUERY_STRING'])
    bodyData = ''
    if environ['REQUEST_METHOD'] == 'POST':
        bodyData = environ['wsgi.input'].read().decode("utf-8")

    if path == '/ajax/getItemList':
        result = GetItemList(queryString, bodyData)
        if result:
            response = '200 OK'
            responseContentType = 'application/javascript'
            headerList.append(('Content-Type', responseContentType))
            responseBody = result

    elif path == '/ajax/getItemPresetList':
        result = GetItemListFromPreset(queryString, bodyData)
        if result:
            response = '200 OK'
            responseContentType = 'application/javascript'
            headerList.append(('Content-Type', responseContentType))
            responseBody = result

    elif path == '/ajax/getShipList':
        result = GetShipList(queryString, bodyData)
        if result:
            response = '200 OK'
            responseContentType = 'application/javascript'
            headerList.append(('Content-Type', responseContentType))
            responseBody = result

    elif path == '/ajax/getShipPresetList':
        result = GetShipListFromPreset(queryString, bodyData)
        if result:
            response = '200 OK'
            responseContentType = 'application/javascript'
            headerList.append(('Content-Type', responseContentType))
            responseBody = result

    elif path == '/ajax/getShortenedUrl':
        result = GetShortenedUrl(queryString)
        if result:
            response = '200 OK'
            responseContentType = 'application/json'
            headerList.append(('Content-Type', responseContentType))
            responseBody = json.dumps(result)
        else:
            response = '400 Bad Request'
            responseContentType = 'text/html'
            headerList.append(('Content-Type', responseContentType))

    elif path == '/s':
        result = GetFullPathForToken(queryString)
        if result:
            response = '301 Moved Permanently'
            headerList.append(('Location', result))

    elif path == '/js/getPresetListForItemFinder':
        result = GetPresetListForItemFinder(queryString)
        if result:
            response = '200 OK'
            responseContentType = 'application/javascript'
            headerList.append(('Content-Type', responseContentType))
            responseBody = "var presetList = {};".format(result)

    elif path == '/js/getPresetListForShipFinder':
        result = GetPresetListForShipFinder(queryString)
        if result:
            response = '200 OK'
            responseContentType = 'application/javascript'
            headerList.append(('Content-Type', responseContentType))
            responseBody = "var presetList = {};".format(result)

    elif path == '/js/getFilterListForItemFinder':
        result = GetFilterListForItemFinder(queryString)
        if result:
            response = '200 OK'
            responseContentType = 'application/javascript'
            headerList.append(('Content-Type', responseContentType))
            responseBody = "var filterList = {};".format(result)

    elif path == '/js/getFilterListForShipFinder':
        result = GetFilterListForShipFinder(queryString)
        if result:
            response = '200 OK'
            responseContentType = 'application/javascript'
            headerList.append(('Content-Type', responseContentType))
            responseBody = "var filterList = {};".format(result)

    elif path == '/js/getUnreleasedRaceList':
        from SFIWikiBotLib import Config
        response = '200 OK'
        responseContentType = 'application/javascript'
        headerList.append(('Content-Type', responseContentType))
        responseBody = "var unreleasedRaceList = {};".format(
            json.dumps(Config.unreleasedRaceList))

    elif path == '/RefreshData':
        ItemUtils.Initialize()
        ShipUtils.Initialize()
        GalaxyUtils.Initialize()
        SmallConstants.Initialize()

        response = '200 OK'
        responseContentType = 'text/html'
        headerList.append(('Content-Type', responseContentType))
        responseBody = "Success"

    elif path == '/Debug':
        from SFIWikiBotLib import Config
        response = '200 OK'
        responseContentType = 'text/html'
        headerList.append(('Content-Type', responseContentType))
        responseBody = "User: " + Config.botUsername

    start_response(response, headerList)
    return [responseBody]