コード例 #1
0
 def data():
     for planeID in planeIDs:
         idTypeList = [[planeID, 'plane']]
         deleteFromCache(idTypeList, ifacename)
         ids, types = map(idFromList, splitIDTypeList(idTypeList))
         if accountUI and set(UI_CALLBACKS.get(ids, {}).get(types, {}).get(ifacename, [])):
             yield [{ifacename: {}}, idTypeList]
コード例 #2
0
def addUICallback(respdata, callback, ifacehandler, data = UI_CALLBACKS, force = False):
    for ifaces, idTypeList in respdata:
        ids, types = map(idFromList, splitIDTypeList(idTypeList))
        for iface in ifaces:
            callbacks = set(data.get(ids, {}).get(types, {}).get(iface, []))
            if force or ifaces[iface]:
                if callback and callback not in callbacks:
                    addToCache(ids, types, iface, callback)
            elif callbacks:
                removeFromCache(ids, types, iface, callbacks)
コード例 #3
0
def removeUICallback(requestdata, callback, ifacehandler, data = UI_CALLBACKS):
    for ifaces, idTypeList in requestdata:
        ids, types = map(idFromList, splitIDTypeList(idTypeList))
        for iface in ifaces:
            callbacks = set(data.get(ids, {}).get(types, {}).get(iface, []))
            if callback and callback in callbacks:
                removeFromCache(ids, types, iface, callback)
            elif callback is None and callbacks:
                removeFromCache(ids, types, iface, callbacks)

    return
コード例 #4
0
def processIFaceData(headers, respdata):
    for data, idTypeList in respdata:
        typeList = splitIDTypeList(idTypeList)[1]
        for ifacename in data:
            if data[ifacename] and not headers[0] == int(
                    IS_CLIENT) and getOblocation(
                        ifacename, typeList) == OB_LOCATION.MIXED:
                data[ifacename] = getAdapter(ifacename, typeList, silent=True)(
                    getPlayer(), data[ifacename], idTypeList=idTypeList)

    ob = [headers, respdata, ErrorCodes.SUCCESS]
    debug_observable.IfaceDebugOutput(COMMAND_TYPES.RESPONSE, ob=ob)
コード例 #5
0
    def __call__(self, account, ob, **kw):
        idList, typeList = splitIDTypeList(kw['idTypeList'])
        if 'plane' in typeList and 'birthday' in typeList:
            try:
                planeID, index = idList
                if index >= 0 and db.DBLogic.g_instance.isAircraftInDB(
                        planeID):
                    return {'bonus': getBirthdayBonus(account, index, planeID)}
            except:
                pass

        return None
コード例 #6
0
ファイル: cache.py プロジェクト: SEA-group/wowp_scripts
def actualizeCacheData(idTypeList, ifaceName):
    deleteFromCache(idTypeList, ifaceName)
    ids, types = map(idFromList, splitIDTypeList(idTypeList))
    deleteFromCache(idTypeList, ifaceName)
    if set(UI_CALLBACKS.get(ids, {}).get(types, {}).get(ifaceName, [])):
        from gui.WindowsManager import g_windowsManager
        accountUI = g_windowsManager.getAccountUI()
        if accountUI:
            accountUI.viewIFace([[{ifaceName: {}}, idTypeList]])
        else:
            LOG_ERROR(
                "accountUI is not ready. data hasn't been updated on subscribed list"
            )
コード例 #7
0
 def __call__(self, account, ob, **kw):
     ob = super(IMessageAdapter, self).__call__(account, ob, **kw)
     idTypeList = kw['idTypeList']
     idList, typeList = splitIDTypeList(idTypeList)
     ids = idFromList(idList)
     types = idFromList(typeList)
     cache.setdefault(ids, {}).setdefault(types, 1)
     import IMessageHandler
     if ob['msgType'] == MESSAGE_TYPE.MESSAGE_GROUP:
         modifiedob = IMessageHandler.handleMessageGroup(ob)
     else:
         modifiedob = IMessageHandler.handle(ob)
     LOG_TRACE('IMessageAdapter. modifiedob %s' % str(modifiedob))
     return modifiedob
コード例 #8
0
ファイル: onRentEvent.py プロジェクト: SEA-group/wowp_scripts
def _updateRentedPlane(planeID):
    ifacename = 'IRent'
    idTypeList = [[planeID, 'plane']]
    ids, types = map(idFromList, splitIDTypeList(idTypeList))
    deleteFromCache(idTypeList, ifacename)
    if set(UI_CALLBACKS.get(ids, {}).get(types, {}).get(ifacename, [])):
        accountUI = g_windowsManager.getAccountUI()
        if accountUI:
            accountUI.viewIFace([[{ifacename: {}}, idTypeList]])
        else:
            LOG_ERROR('accountUI is not ready. IRent not called')
    if planeID in RENT_CALLBACKS:
        BigWorld.cancelCallback(RENT_CALLBACKS[planeID])
    RENT_CALLBACKS[planeID] = BigWorld.callback(UPDATER_PERIOD, partial(_updateRentedPlane, planeID))
コード例 #9
0
def getObject(idTypeList, account=None):
    initDB()
    idList, typeList = splitIDTypeList(idTypeList)
    if idList and typeList:
        if len(idList) > 1:
            obList = map(
                lambda x: (x[0] if x[0] is None else getObject([x], account)),
                idTypeList)
            return connectors.get(idFromList(typeList),
                                  lambda x, _: x)(obList, account)
        elif idList[0] is None:
            return
        else:
            return connectors.get(typeList[0], lambda x, _: x)(idList[0],
                                                               account)
    return
コード例 #10
0
    def __separateBuilder(self, ifacename, parentIfacename, ifacedata,
                          idTypeList, result):
        idList, typeList = splitIDTypeList(idTypeList)
        ids = idFromList(idList)
        types = idFromList(typeList)
        piface = getIface(parentIfacename)
        parentdata = {}
        for attr in piface.attr:
            attrdata = ifacedata.get(attr, None)
            if attrdata is not None:
                parentdata[attr] = attrdata

        result.setdefault(ids, {}).setdefault(types, {}).setdefault(
            ifacename, {}).setdefault(parentIfacename, {}).update(parentdata)
        for parentIfacename in getIface(parentIfacename).parent:
            self.__separateBuilder(ifacename, parentIfacename, ifacedata,
                                   idTypeList, result)

        return
コード例 #11
0
        def saveIfaceData(transformedResponse, ifacesdata):
            for ifacedata in ifacesdata:
                ifaces, idTypeList = ifacedata
                idList, typeList = splitIDTypeList(idTypeList)
                ids = idFromList(idList)
                types = idFromList(typeList)
                for parentIfacename in ifaces:
                    names = parentIfacename.split(':')
                    try:
                        parent, ifacename = (
                            parentIfacename,
                            parentIfacename) if len(names) == 1 else names
                    except ValueError:
                        LOG_ERROR('names: {0}'.format(names))
                        parent, ifacename = names[0], names[-1]

                    transformedResponse.setdefault(ids, {}).setdefault(
                        types, {}).setdefault(parent, {}).setdefault(
                            ifacename, {}).update(ifaces[parentIfacename]
                                                  or {})
コード例 #12
0
        def cacheHandler(request, reqFromCache):
            newrequest = []
            for data, idTypeList in request:
                requestifaces = {}
                idList, typeList = splitIDTypeList(idTypeList)
                ids = idFromList(idList)
                types = idFromList(typeList)
                for ifacename in data:
                    ifacedata = getFromCache(idTypeList, ifacename)
                    if ifacedata is None:
                        requestifaces[ifacename] = data[ifacename]
                    else:
                        reqFromCache.append([{
                            ifacename: data[ifacename]
                        }, idTypeList])

                if requestifaces:
                    newrequest.append([requestifaces, idTypeList])

            return newrequest
コード例 #13
0
 def cachedata(ifacesFromCache):
     for obid in transformedResponse:
         for obtype in transformedResponse[obid]:
             idTypeList = joinIDTypeList(listFromId(obid),
                                         listFromId(obtype))
             idList, typeList = splitIDTypeList(idTypeList)
             ids = idFromList(idList)
             types = idFromList(typeList)
             for parentName, ifaces in transformedResponse[obid][
                     obtype].iteritems():
                 for ifacename, attrs in ifaces.iteritems():
                     if not ifacesFromCache.get(ids, {}).get(
                             types, {}).get(ifacename, False):
                         if attrs:
                             setToCache(idTypeList, ifacename,
                                        attrs)
                         else:
                             deleteFromCache(idTypeList, ifacename)
                     else:
                         transformedResponse[obid][obtype][
                             parentName][ifacename] = getFromCache(
                                 idTypeList, ifacename) or {}
コード例 #14
0
ファイル: cache.py プロジェクト: SEA-group/wowp_scripts
def getFromCache(idTypeList, ifaceName):
    global INITIALIZED
    if not INITIALIZED:
        LOG_ERROR('Cache is not initialized')
        return
    else:
        try:
            from exchangeapi.AdapterUtils import getOblocationDBObject
            _, typeList = splitIDTypeList(idTypeList)
            expiringTime = getOblocationDBObject(ifaceName,
                                                 typeList).expiringTime
        except:
            expiringTime = None

        cacheID = generateID(idTypeList, ifaceName)
        data = memCacheUtility.getFromCache(cacheID, expiringTime)
        if data is None:
            data = cacheUtility.getFromCache(
                cacheID if cacheUtility.ID_TYPE == int else generateUUID(
                    idTypeList, ifaceName), expiringTime)
            if data:
                memCacheUtility.setToCache(cacheID, data)
        return data
コード例 #15
0
ファイル: cache.py プロジェクト: SEA-group/wowp_scripts
def setToCache(idTypeList, ifaceName, data, event=True):
    global EXPIRING_CALLBACKS
    if not INITIALIZED:
        LOG_ERROR('Cache is not initialized')
        return False
    else:
        try:
            cacheType = getIface(ifaceName).cacheType
        except IfaceNotFound:
            cacheType = CACHE_TYPE.FULL_CACHE

        if cacheType == CACHE_TYPE.NONE:
            return False
        try:
            from exchangeapi.AdapterUtils import getOblocationDBObject
            _, typeList = splitIDTypeList(idTypeList)
            expiringTime = getOblocationDBObject(ifaceName,
                                                 typeList).expiringTime
        except:
            expiringTime = None

        if expiringTime:
            EXPIRING_CALLBACKS.append(
                BigWorld.callback(
                    expiringTime,
                    partial(actualizeCacheData, idTypeList, ifaceName)))
        cacheID = generateID(idTypeList, ifaceName)
        memCacheUtility.setToCache(cacheID, data)
        if cacheType == CACHE_TYPE.FULL_CACHE:
            cacheUtility.setToCache(
                cacheID if cacheUtility.ID_TYPE == int else generateUUID(
                    idTypeList, ifaceName), data)
        if event:
            from exchangeapi.EventUtils import generateEvent
            generateEvent('', 'settocache', ifaceName, idTypeList, None, data,
                          None)
        return True
コード例 #16
0
        def onResponseObBuilt(transformedResponse, reqFromCache, headers,
                              code):
            if self.__requestCount:
                return

            def data():
                for obid in transformedResponse:
                    for obtype in transformedResponse[obid]:
                        idTypeList = joinIDTypeList(listFromId(obid),
                                                    listFromId(obtype))
                        ifacesdata = {}
                        for parent, ifaces in transformedResponse[obid][
                                obtype].iteritems():
                            ifacedata = {}
                            for attrs in ifaces.itervalues():
                                ifacedata.update(attrs)

                            ifacesdata[parent] = ifacedata

                        yield [ifacesdata, idTypeList]

            def cachedata(ifacesFromCache):
                for obid in transformedResponse:
                    for obtype in transformedResponse[obid]:
                        idTypeList = joinIDTypeList(listFromId(obid),
                                                    listFromId(obtype))
                        idList, typeList = splitIDTypeList(idTypeList)
                        ids = idFromList(idList)
                        types = idFromList(typeList)
                        for parentName, ifaces in transformedResponse[obid][
                                obtype].iteritems():
                            for ifacename, attrs in ifaces.iteritems():
                                if not ifacesFromCache.get(ids, {}).get(
                                        types, {}).get(ifacename, False):
                                    if attrs:
                                        setToCache(idTypeList, ifacename,
                                                   attrs)
                                    else:
                                        deleteFromCache(idTypeList, ifacename)
                                else:
                                    transformedResponse[obid][obtype][
                                        parentName][ifacename] = getFromCache(
                                            idTypeList, ifacename) or {}

            ifacesFromCache = {}
            for reqData, idTypeList in reqFromCache:
                idList, typeList = splitIDTypeList(idTypeList)
                ids = idFromList(idList)
                types = idFromList(typeList)
                for ifacename in reqData:
                    reqData[ifacename] = getFromCache(idTypeList,
                                                      ifacename) or {}
                    ifacesFromCache.setdefault(ids, {}).setdefault(
                        types, {})[iface_name(ifacename)] = True

            saveIfaceData(transformedResponse, reqFromCache)
            idata = list(data())
            if code == ErrorCodes.SUCCESS:
                if self.__generateEvent:
                    responseEventGenerate(headers, idata)
                cachedata(ifacesFromCache)
            responseob = [
                headers, idata if code == ErrorCodes.SUCCESS else
                ErrorCodes.ERROR_DESCRIPTION.get(code, 'Unknown error'), code
            ]
            self.__onBuildFinishedCallback(responseob)
コード例 #17
0
def sendDataToUICallbacks(headers, respdata, callback, ifacehandler = None, data = UI_CALLBACKS, fromserver = False, broadcast = True, proccesedIfaces = None):
    data = dict(data)
    from Helpers.ExchangeObBuilder import ExchangeObBuilder, cacheIFaceData, responseEventGenerate
    from Helpers.cache import getFromCache
    proccesedIfaces = proccesedIfaces or dict()
    if callback:
        ifacehandler.addResponseCallbackToQueue(partial(ifacehandler.call_1, callback, convertIfaceDataForUI(respdata), 0))
    for ifaces, idTypeList in respdata:
        ids, types = map(idFromList, splitIDTypeList(idTypeList))
        for ifacename in ifaces:
            if ifacename in proccesedIfaces.get(ids, {}).get(types, set([])):
                continue
            ifacedata = {ifacename: ifaces[ifacename]}
            idata = [[ifacedata, idTypeList]]
            iface = getIface(ifacename)
            if fromserver:
                from Helpers.ExchangeObBuilder import processIFaceData
                processIFaceData([int(not IS_CLIENT), METHODTOINDEX['view']], idata)
                responseEventGenerate(headers, idata)
                cacheIFaceData(idata)
                if ifacedata[ifacename]:
                    for c in getDefaultCallbacks(ifacename, ifacehandler, data):
                        addUICallback([[{ifacename: True}, idTypeList]], c, ifacehandler, data)

                    data.update(UI_CALLBACKS)
                if iface.parent:

                    def constructed(ifacehandler, fromserver, broadcast, proccesedIfaces, responseob):
                        if responseob[-1] == ErrorCodes.SUCCESS:
                            responseEventGenerate([int(not consts.IS_CLIENT), METHODTOINDEX['edit']], responseob[1])
                            sendDataToUICallbacks(responseob[0], responseob[1], None, ifacehandler, data, fromserver, broadcast, proccesedIfaces)
                        return

                    requestob = [[int(consts.IS_CLIENT)], [[{ifacename: {}}, idTypeList]], METHODTOINDEX['view']]
                    builder = ExchangeObBuilder(requestob, False)
                    builder.setFinishCallback(partial(constructed, ifacehandler, False, broadcast, proccesedIfaces))
                    builder.build()
                    continue
            elif ifacedata[ifacename]:
                for c in getDefaultCallbacks(ifacename, ifacehandler, data):
                    addUICallback([[{ifacename: True}, idTypeList]], c, ifacehandler, data)

                data.update(UI_CALLBACKS)
            proccesedIfaces.setdefault(ids, {}).setdefault(types, set([])).update([ifacename])
            callbacks = set(data.get(ids, {}).get(types, {}).get(ifacename, []))
            if callbacks:
                for parentname in iface.parent:
                    PARENT_INTERFACES.setdefault(ids, {}).setdefault(types, set([])).update([ifacename])

            for item in callbacks:
                if item != callback:
                    if broadcast and ifacehandler:
                        debug_utils.LOG_DEBUG('UICallbackUtils:Iface:response', idata, item)
                        convertedIDTypeList = convertIDTypeListForUI(idTypeList)
                        if not convertedIDTypeList:
                            obid = None
                            obtype = None
                        else:
                            obid = convertedIDTypeList[0][0]
                            obtype = convertedIDTypeList[0][1]
                        ifacehandler.addResponseCallbackToQueue(partial(ifacehandler.call_1, item, [[ifacedata, obid, obtype]] if idTypeList is not None and len(idTypeList) < 2 else [[ifacedata, convertedIDTypeList]], 0))
                    if not fromserver and ifacedata[ifacename]:
                        addUICallback(idata, item, ifacehandler, data)
                    elif not ifacedata[ifacename]:
                        removeUICallback(idata, item, ifacehandler, data)

            if broadcast and ifacehandler:
                for parentname in iface.parent:
                    if parentname in proccesedIfaces.get(ids, {}).get(types, set([])):
                        continue
                    piface = getIface(parentname)
                    cacheddata = getFromCache(idTypeList, parentname) or {}
                    parentdata = dict(((attr, ifaces[ifacename].get(attr, cacheddata.get(attr, None))) for attr in piface.attr))
                    if parentdata:
                        iparentdata = [[{parentname: parentdata}, idTypeList]]
                        responseEventGenerate([int(consts.IS_CLIENT), METHODTOINDEX['edit']], iparentdata)
                        sendDataToUICallbacks(headers, iparentdata, None, ifacehandler, data, fromserver, broadcast, proccesedIfaces)

                pnames = list(PARENT_INTERFACES.get(ids, {}).get(types, set([])))
                for pname in pnames:
                    if pname in proccesedIfaces.get(ids, {}).get(types, set([])):
                        continue

                    def constructed(ifacehandler, broadcast, proccesedIfaces, responseob):
                        if responseob[-1] == ErrorCodes.SUCCESS:
                            responseEventGenerate([int(consts.IS_CLIENT), METHODTOINDEX['edit']], responseob[1])
                            sendDataToUICallbacks(responseob[0], responseob[1], None, ifacehandler, data, False, broadcast, proccesedIfaces)
                        return

                    requestob = [[int(consts.IS_CLIENT)], [[{pname: {}}, idTypeList]], METHODTOINDEX['view']]
                    builder = ExchangeObBuilder(requestob, False)
                    builder.setFinishCallback(partial(constructed, ifacehandler, broadcast, proccesedIfaces))
                    builder.build()

    return
コード例 #18
0
    def __call__(self, account, ob, **kw):
        if ob is None:
            return
        else:
            cmpUpgrade = None
            cmpUpgradeID = None
            weaponConfig = None
            slotID = None
            upgrade = None
            upgradeID = None
            plane = None
            _, typeList = splitIDTypeList(kw['idTypeList'])
            if isinstance(ob, list):
                for idx in xrange(0, len(typeList)):
                    if typeList[idx] == 'plane':
                        plane = ob[idx]
                    elif typeList[idx] == 'upgrade':
                        if upgradeID is None:
                            upgrade = ob[idx]
                            upgradeID = kw['idTypeList'][idx][0]
                        else:
                            cmpUpgrade = ob[idx]
                            cmpUpgradeID = kw['idTypeList'][idx][0]
                    elif typeList[idx] == 'weaponConfig':
                        weaponConfig = ob[idx]
                    elif typeList[idx] == 'weaponslot':
                        slotID = ob[idx].id

            else:
                upgrade = ob
            adaptedOb = super(IModuleDescriptionAdapter,
                              self).__call__(account, ob, **kw)
            if upgrade is not None:
                outName, specs, planesSet, shortDescription = getUpgradeSpecs(
                    upgrade, plane.id if plane is not None else None,
                    cmpUpgrade, slotID, weaponConfig)
            elif weaponConfig is None or slotID is None or cmpUpgradeID is None or cmpUpgrade.type not in UPGRADE_TYPE.WEAPON:
                return adaptedOb
            adaptedOb['configComparison'] = []
            adaptedOb['requiredModules'] = []
            dbInstance = db.DBLogic.g_instance
            cmpGlobalID = 0
            if cmpUpgradeID is not None:
                import BWPersonality
                lch = BWPersonality.g_lobbyCarouselHelper
                lobbyAirplane = lch.getCarouselAirplane(
                    plane.id) or getLobbyAirplane(plane.id)
                upgradeName = upgrade.name if upgrade is not None else None
                cmpName = cmpUpgrade.name if cmpUpgrade is not None else None
                if lobbyAirplane is not None:
                    upgrades = [
                        x['name']
                        for x in lobbyAirplane.modules.getInstalled()
                    ]
                    weaponList = lobbyAirplane.weapons.getInstalledWeaponsList(
                    )
                    if not upgrades:
                        planeConfig = airplanesConfigurations[
                            airplanesDefaultConfigurations[plane.id]]
                        upgrades = planeConfig.modules
                        weaponList = planeConfig.weaponSlots
                    cmpGlobalID, newUpgrades, newWeaponList = adjustPlaneConfig(
                        lobbyAirplane.planeID, upgrades, weaponList,
                        upgradeName, cmpName, slotID, weaponConfig)
                    oldGlobalID = db.DBLogic.createGlobalID(
                        lobbyAirplane.planeID, upgrades, weaponList)
                    requiredModules = getDiffModules(oldGlobalID, cmpGlobalID,
                                                     upgradeName,
                                                     (slotID, weaponConfig))
                    for upgradeName in requiredModules:
                        reqUpgrade = dbInstance.getUpgradeByName(upgradeName)
                        name, _, _, _ = getUpgradeSpecs(
                            reqUpgrade,
                            plane.id if plane is not None else None, None,
                            slotID, weaponConfig)
                        adaptedOb['requiredModules'].append(name)

                    cmpLobbyAirplane = lobbyAirplane.previewPreset(
                        newUpgrades, [{
                            'slot': x[0],
                            'configuration': x[1]
                        } for x in newWeaponList])
                    comparisonSpecs = cmpLobbyAirplane.getGroupedDescriptionFields(
                        True, lobbyAirplane, cmpGlobalID, False)
                    for el in comparisonSpecs:
                        for i, j in el.__dict__.iteritems():
                            if i != 'main':
                                continue
                            specObj = None
                            if j is not None:
                                specObj = j.__dict__
                            if specObj and specObj['comparisonValue']:
                                adaptedOb['configComparison'].append(specObj)

            if not adaptedOb['configComparison']:
                adaptedOb['configComparison'] = None
            if upgrade is not None:
                gunData = dbInstance.getGunData(upgrade.name)
                if gunData is None:
                    moduleType = localizeComponents(
                        MODULE_GROUP_NAME.get(
                            getattr(upgrade, 'moduleGroup', None),
                            MODULE_GROUP_NAME[upgrade.type]))
                else:
                    profileName = gunData.gunProfileName.upper()
                    if profileName == 'MACHINEGUN_SMALL':
                        profileName = 'MACHINE_GUN_LOW'
                    else:
                        profileName = profileName.replace(
                            'MACHINEGUN_SMALL', 'MACHINE_GUN')
                    profileName = profileName.replace('CANNON_HIGH_VULCAN',
                                                      'CANNON_HIGH')
                    moduleType = localizeLobby(
                        '{0}_DESCRIPTION'.format(profileName))
                adaptedOb['name'] = '{0} {1}'.format(moduleType, outName)
                adaptedOb['type'] = upgrade.type
                adaptedOb['description'] = shortDescription
                if hasattr(upgrade, 'level'):
                    adaptedOb['level'] = upgrade.level
                else:
                    adaptedOb['level'] = 0
                adaptedOb['specsList'] = [spec.__dict__ for spec in specs]
                adaptedOb['airplanesList'] = map(
                    lambda x: localizeAirplane(dbInstance.getAircraftName(x)),
                    filter(lambda x: x in planesSet,
                           dbInstance.getShopPlaneList()))
                adaptedOb['suitablePlaneIDs'] = list(planesSet)
                adaptedOb['icoPath'] = get48ModuleIconPath(
                    getattr(upgrade, 'iconPath', ICON_MODULE_DEFAULT_PATH))
                isArmoredTargetEffective = EFFECTIVE_AGAINST_ARMORED_OBJECTS.NORMAL
                if upgrade.type in [UPGRADE_TYPE.BOMB, UPGRADE_TYPE.ROCKET]:
                    isArmoredTargetEffective = EFFECTIVE_AGAINST_ARMORED_OBJECTS.IS_EFFECTIVE
                if upgrade.type == UPGRADE_TYPE.GUN:
                    isArmoredTargetEffective = EFFECTIVE_AGAINST_ARMORED_OBJECTS.NOT_EFFECTIVE if gunData.caliber < MIN_CALIBER else EFFECTIVE_AGAINST_ARMORED_OBJECTS.LOW_EFFECTIVE
                adaptedOb['armoredTargetEffective'] = isArmoredTargetEffective
                adaptedOb['buyAvailable'] = getattr(upgrade, 'buyAvailable',
                                                    True)
                if upgrade.type == UPGRADE_TYPE.GUN:
                    compData = gunData
                elif upgrade.type in UPGRADE_TYPE.SHELL:
                    compData = dbInstance.getComponentByName(
                        UPGRADE_TYPE_TO_COMPONENT_TYPE[upgrade.type],
                        upgrade.name)
                elif upgrade.type == UPGRADE_TYPE.TURRET:
                    turret = dbInstance.getTurretData(upgrade.name)
                    compData = dbInstance.getGunData(turret.hangarSimilarGun)
                else:
                    compData = None
                if compData is not None and hasattr(compData, 'tag'):
                    adaptedOb['propsList'] = [[localizeLobby(x.name), x.type]
                                              for x in compData.tag]
                else:
                    adaptedOb['propsList'] = []
                adaptedOb['cmpGlobalID'] = cmpGlobalID
            else:
                adaptedOb['name'] = ''
                adaptedOb['type'] = -1
                adaptedOb['description'] = ''
                adaptedOb['level'] = 0
                adaptedOb['specsList'] = []
                adaptedOb['airplanesList'] = []
                adaptedOb['suitablePlaneIDs'] = []
                adaptedOb['icoPath'] = ''
                adaptedOb['armoredTargetEffective'] = False
                adaptedOb['buyAvailable'] = False
                adaptedOb['cmpGlobalID'] = 0
            return adaptedOb
コード例 #19
0
    def __call__(self, account, obList, **kw):
        import BWPersonality
        lch = BWPersonality.g_lobbyCarouselHelper
        globalID = kw['idTypeList'][0][0]
        planeID = db.DBLogic.g_instance.getPlaneIDByGlobalID(globalID)
        ob = None
        measurementSystem = None
        obCompare = None
        _, typeList = splitIDTypeList(kw['idTypeList'])
        if isinstance(obList, list):
            for idx in xrange(0, len(typeList)):
                if typeList[idx] == 'measurementSystem':
                    measurementSystem = MeasurementSystem(obList[idx])
                elif typeList[idx] == 'planePreset':
                    if ob is None:
                        ob = obList[idx]
                    else:
                        obCompare = obList[idx]

        if obCompare is not None:
            airplaneForCompare = lch.getCarouselAirplane(
                obCompare['plane'].planeID) or getLobbyAirplane(
                    obCompare['plane'].planeID)
        else:
            airplaneForCompare = None
        carouselAirplane = lch.getCarouselAirplaneSelected()
        if carouselAirplane is not None:
            currentPlaneID = carouselAirplane.planeID
            installedGlobalID = lch.inventory.getInstalledUpgradesGlobalID(
                currentPlaneID) if lch.inventory.isAircraftBought(
                    currentPlaneID) else 0
        else:
            installedGlobalID = 0
        modify = globalID == installedGlobalID
        adaptedOb = super(IConfigSpecsAdapter,
                          self).__call__(account, ob, **kw)
        if ob is not None:
            plane = ob['plane']
            lobbyPlane = lch.getCarouselAirplane(
                plane.planeID) or getLobbyAirplane(plane.planeID)
            equipment = lch.inventory.getEquipment(planeID)
            crewList = lch.inventory.getCrewList(planeID)
            if airplaneForCompare is None:
                projectiles = lobbyPlane.weapons.getInstalledProjectiles()
            else:
                projectiles = None
            specs = getPerformanceSpecsTable(globalID, modify, projectiles,
                                             equipment, crewList)
            if specs is not None:
                for key, value in specs.__dict__.iteritems():
                    if key in self._iface.attr:
                        ob[key] = value

            specs = lobbyPlane.getGroupedDescriptionFields(
                True, airplaneForCompare, globalID, modify, measurementSystem)
            adaptedOb['specs'] = []
            for el in specs:
                group = {}
                for i, j in el.__dict__.iteritems():
                    if isinstance(j, list):
                        vlist = []
                        for jel in j:
                            vlist.append(jel.__dict__)

                        group[i] = vlist
                    elif j is not None:
                        group[i] = j.__dict__

                adaptedOb['specs'].append(group)

        return adaptedOb
コード例 #20
0
    def __call__(self, account, ob, **kw):
        _, typeList = splitIDTypeList(kw['idTypeList'])
        weapon = None
        measurementSystem = None
        if isinstance(ob, list):
            for idx in xrange(0, len(typeList)):
                if typeList[idx] == 'measurementSystem':
                    measurementSystem = MeasurementSystem(ob[idx])
                else:
                    weapon = ob[idx]

        else:
            weapon = ob
        adaptedOB = super(IWeaponDescriptionAdapter,
                          self).__call__(account, weapon, **kw)
        if weapon is None:
            LOG_ERROR('IWeaponDescriptionAdapter: weapon not found', ob, kw)
            return adaptedOB
        else:
            adaptedOB['name'] = localizeComponents('WEAPON_NAME_%s' %
                                                   weapon.name)
            weaponType = kw['weaponType']
            if weaponType in UPGRADE_TYPE.SHELL:
                adaptedOB['iconPathSmall'] = weapon.iconPathSmall
            else:
                adaptedOB['iconPathSmall'] = ''
            dbInstance = db.DBLogic.g_instance
            adaptedOB['caliber'] = weapon.caliber
            upgrade = dbInstance.upgrades.get(weapon.name, None)
            if upgrade is not None:
                adaptedOB['iconPath'] = get48ModuleIconPath(
                    getattr(upgrade, 'iconPath', ICON_MODULE_DEFAULT_PATH))
                adaptedOB['iconPathSmall'] = get24ModuleIconPath(
                    getattr(upgrade, 'iconPath', ICON_MODULE_DEFAULT_PATH))
                adaptedOB['upgradeID'] = upgrade.id
                adaptedOB[
                    'suitablePlaneIDs'] = dbInstance.getSuitablePlanesForUpgrade(
                        upgrade)
                if adaptedOB['suitablePlaneIDs']:
                    if dbInstance.isPlanePremium(
                            adaptedOB['suitablePlaneIDs'][0]):
                        adaptedOB['name'] = '{0} {1}'.format(
                            adaptedOB['name'],
                            localizeComponents('WEAPON_NAME_GOLDBELT'))
                if upgrade.type == UPGRADE_TYPE.ROCKET or upgrade.type == UPGRADE_TYPE.BOMB:
                    adaptedOB['description'] = '\n'.join([
                        '{0} {1}{2} '.format(x.name, x.value, x.unit)
                        for x in getShellDescription(weapon, measurementSystem)
                    ])
                    adaptedOB['shortDescription'] = '{0} {1}'.format(
                        localizeLobby(
                            'LOBBY_MAINTENANCE_MODULE_PARAMETER_DAMAGE'),
                        weapon.explosionDamage)
                else:
                    adaptedOB['description'] = ''
                    adaptedOB['shortDescription'] = ''
                adaptedOB['buyAvailable'] = getattr(upgrade, 'buyAvailable',
                                                    True)
                if upgrade.type == UPGRADE_TYPE.GUN:
                    gunData = dbInstance.getGunData(upgrade.name)
                    adaptedOB['maxDistance'] = round(
                        measurementSystem.getMeters(gunData.bulletFlyDist /
                                                    consts.WORLD_SCALING))
                else:
                    adaptedOB['maxDistance'] = 0
            return adaptedOB