def init(achievesMappingXmlPath): global BATTLE_APPROACHABLE_ACHIEVES global BATTLE_ACHIEVES_WITH_RIBBON global BATTLE_ACHIEVES_RIGHT global FORT_BATTLE_ACHIEVES_RIGHT raise achievesMappingXmlPath or AssertionError( 'Invalid achievements mapping file') ctx, section = resource_helper.getRoot(achievesMappingXmlPath) for ctx, subSection in resource_helper.getIterator( ctx, section['achievements']): try: item = resource_helper.readItem(ctx, subSection, name='achievement') if not item.name: continue block, name = tuple(item.name.split(':')) if block not in ACHIEVEMENT_BLOCK.ALL: raise Exception('Unknown block name', (block, name)) if 'type' not in item.value or item.value[ 'type'] not in ACHIEVEMENT_TYPE.ALL: raise Exception('Unknown achievement type', (block, name), item.value) if 'section' not in item.value or item.value[ 'section'] not in ACHIEVEMENT_SECTION.ALL: raise Exception('Unknown achievement section', (block, name), item.value) if 'mode' not in item.value or item.value[ 'mode'] not in _MODE_CONVERTER: raise Exception('Unknown achievement mode', (block, name), item.value) value = dict(item.value) value['mode'] = _MODE_CONVERTER[item.value['mode']] if 'weight' not in value: value['weight'] = -1.0 ACHIEVEMENTS[block, name] = value except: LOG_CURRENT_EXCEPTION() BATTLE_ACHIEVES_WITH_RIBBON = tuple( resource_helper.readList(ctx, section['battleAchievesWithRibbon']).value) BATTLE_ACHIEVES_RIGHT = tuple( resource_helper.readList(ctx, section['battleResultsRight']).value) FORT_BATTLE_ACHIEVES_RIGHT = tuple( resource_helper.readList(ctx, section['fortBattleResultsRight']).value) BATTLE_APPROACHABLE_ACHIEVES = tuple( resource_helper.readList(ctx, section['approachableAchieves']).value)
def _readFile(self): res = ResMgr.openSection(self._filePath) if res: try: processor = _LicenseXMLProcessor() for child in res.values(): result = processor.execute(child, result=[]) if len(result) > 0: self._text.extend(result) except: LOG_CURRENT_EXCEPTION() ResMgr.purge(self._filePath, True) else: LOG_ERROR("_readFile - can't open resource: %s" % self._filePath)
def initGroups(self, scaleFactor): if BigWorld.isForwardPipeline(): return try: for group in self.__cfg['groups'].items(): BigWorld.wg_addDecalGroup(group[0], group[1]['lifeTime'] * scaleFactor, group[1]['trianglesCount'] * scaleFactor) for tex in self.__cfg['textures'].items(): index = BigWorld.wg_decalTextureIndex(tex[1]) if index == -1: LOG_ERROR("texture '%s' is not exist or to more textures added to the texture atlas.Max textures count is 16." % tex[1]) else: self.__texMap[tex[0]] = index except Exception: LOG_CURRENT_EXCEPTION()
def fini(self): self.eManager.clear() if self._guiRef is None or self._guiRef() is None: return else: try: self.call('common.closeAllWindows') movie = self.uiHolder.movie movie.invoke(('_root.tutorialLoader.unloadTutorial', [])) LOG_DEBUG("unload 'TutorialLayout.swf'") except Exception: LOG_CURRENT_EXCEPTION() return False self.dispossessUI() return
def save(accountName, battleResults): fileHandler = None try: arenaUniqueID = battleResults[0] folderName = getFolderName(accountName, arenaUniqueID) if not os.path.isdir(folderName): os.makedirs(folderName) fileName = os.path.join(folderName, '%s.dat' % arenaUniqueID) fileHandler = open(fileName, 'wb') cPickle.dump((BATTLE_RESULTS_VERSION, battleResults), fileHandler, -1) except Exception: LOG_CURRENT_EXCEPTION() if fileHandler is not None: fileHandler.close() return
def savePeripheryTL(self, peripheryID, delta=STORED_AS_RECOMMEND_DELTA): if not AUTO_LOGIN_QUERY_ENABLED or not peripheryID: return else: try: loginSec = Settings.g_instance.userPrefs[ Settings.KEY_LOGIN_INFO] if loginSec is not None: value = base64.b64encode( pickle.dumps((peripheryID, time.time() + delta))) loginSec.writeString('peripheryLifeTime', value) Settings.g_instance.save() except Exception: LOG_CURRENT_EXCEPTION() return
def run(self): while not self._terminated: try: queue = self.__queueRef() if queue is not None: job = queue.get() job.doWork(self) queue.task_done() else: self.terminate() break time.sleep(0.001) except Exception: LOG_CURRENT_EXCEPTION() return
def __loadModels(self, prereqs): try: for modelId in prereqs.keys(): if modelId in prereqs.failedIDs: LOG_ERROR('Failed to load flock model: %s' % modelId) continue model = prereqs[modelId] model.outsideOnly = 1 model.moveAttachments = True model.visible = False self.__models.append(model) animSpeed = random.uniform(self.animSpeedMin, self.animSpeedMax) model.actionScale = animSpeed except Exception: LOG_CURRENT_EXCEPTION()
def setEventParam(self, eventId, paramName, paramValue): e = self.__getEvent(eventId) if e is None: return else: try: soundEventParam = e.param(paramName) if soundEventParam is not None and soundEventParam.value != paramValue: soundEventParam.value = paramValue except Exception: LOG_DEBUG( 'There is error while assigning parameter to the sound', e, paramName) LOG_CURRENT_EXCEPTION() return
def readTemplates(dataSection): global gTemplates gTemplates = dict() try: section = dataSection['templates'] for template in section.items(): templateName = template[1].readString('name', '') selectorTemplate = SelectorDescFactory.create( template[1]['selector']) if selectorTemplate is not None and templateName != '': gTemplates[templateName] = selectorTemplate except Exception: LOG_CURRENT_EXCEPTION() return
def formattedList(self): result = [] for (block, record), value in self.getRecords().iteritems(): try: if _isAchievement(block): if block == ACHIEVEMENT_BLOCK.RARE: continue achieve = _getAchievement(block, record, value) result.append(achieve.userName) else: result.append(i18n.makeString('#quests:details/dossier/%s' % record)) except Exception: LOG_ERROR('There is error while getting bonus dossier record name') LOG_CURRENT_EXCEPTION() return result
def getVisibleVehicles(self): getInfo = self.__arenaDP.getVehicleInfo getProps = self.__arenaDP.getPlayerGuiProps for vehicleID in self.__visible: vehicle = BigWorld.entity(vehicleID) if vehicle is None: continue info = getInfo(vehicleID) props = getProps(vehicleID, info.team) try: if not vehicle.isPlayerVehicle: yield (vehicle.proxy, info, props) except AttributeError: LOG_CURRENT_EXCEPTION() return
def __doShowMessage(self, key, args=None, extra=None): msgText, colors = self.__messages[key] if args is not None: self.__formatEntitiesEx(args, extra=extra) try: msgText = msgText % args except TypeError: LOG_CURRENT_EXCEPTION() if self.__isColorBlind: color = colors[1] else: color = colors[0] LOG_DEBUG('Show message in a battle', self.__name, key) self.__callFlash('ShowMessage', [key, msgText, color]) return
def setForcedGuiControlMode(value, stopVehicle = False, enableAiming = True, cursorVisible = True): if value: flags = GUI_CTRL_MODE_FLAG.CURSOR_ATTACHED if stopVehicle: flags |= GUI_CTRL_MODE_FLAG.MOVING_DISABLED if enableAiming: flags |= GUI_CTRL_MODE_FLAG.AIMING_ENABLED if cursorVisible: flags |= GUI_CTRL_MODE_FLAG.CURSOR_VISIBLE else: flags = GUI_CTRL_MODE_FLAG.CURSOR_DETACHED try: return BigWorld.player().setForcedGuiControlMode(flags) except AttributeError: LOG_CURRENT_EXCEPTION() return False
def __update(self): self.__cbID = BigWorld.callback(self.UPDATE_INTERVAL, self.__update) if self.__thread is None or self.__thread.isAlive(): return else: if self.__thread.result is not None: self.__lastRSS = self.__thread.result for callback in self.__onCompleteCallbacks: try: callback(self.__lastRSS) except Exception: LOG_CURRENT_EXCEPTION() self.__onCompleteCallbacks = set() self.__thread = None return
def getDefences(self, clanDBID=None, filterFunc=None): result = [] for (startTime, direction), data in self.defences.iteritems(): try: item = DefenceItem(startTime, direction, self.peripheryID, *data) if (clanDBID is None or item.getOpponentClanDBID() == clanDBID) and (filterFunc is None or filterFunc(item)): result.append(item) except Exception: LOG_ERROR('Error while building defence item', startTime, direction, data) LOG_CURRENT_EXCEPTION() return sorted(result)
def update(self, manifest): filesToDownload = {} try: unusedApps = self.__storage.getApps() for data in manifest: appName = data['name'] status = data['status'] _logger.debug('Web status for: %s = %s : %s', appName, status['code'], status['description']) host = data['host'] if appName in unusedApps: unusedApps.remove(appName) unusedFiles = self.__storage.getAppFiles(appName) files = data['files'] for curfile in files: url = urlparse.urljoin(host, curfile) key = _generateKey(url) if key not in self.__cache or not self.__storage.isAppFileExist( appName, key): _logger.debug( 'Resource not found in cache. Download from web: %s', url) filesToDownload[url] = appName if key in unusedFiles: unusedFiles.remove(key) for f in unusedFiles: self.__storage.removeAppFile(appName, f) for appName in unusedApps: self.__storage.removeApp(appName) except KeyError: LOG_CURRENT_EXCEPTION() self._prefetchCnt = len(filesToDownload) if self._prefetchCnt > 0: _logger.info('There are %r new files in manifest', self._prefetchCnt) _logger.info('Start downloading...') for url, name in filesToDownload.iteritems(): self.__downloader.download( url, partial(self._onResourceLoaded, name)) else: _logger.info('There are no new files in manifest') self.prefetchEnd()
def loadUserConfig(self): ds = self.__getUserLoginSection() isRememberPwd = GUI_SETTINGS.rememberPassVisible password = '' self.__rememberPwd = False if isRememberPwd: self.__rememberPwd = ds.readBool(self.REMEMBER_PWD_TAG, False) if ds: if GUI_SETTINGS.clearLoginValue: ds.writeString(self.LOGIN_TAG, '') self.__user = self.__getUserLoginName(ds) self.__host = ds.readString(self.HOST_TAG) decrypt = getattr(BigWorld, 'wg_ucpdata', None) if self.PASSWORD_TAG in ds.keys(): password = ds.readString(self.PASSWORD_TAG) decrypt = PasswordObfuscator().unobfuscate else: password = ds.readString(self.PWD_SECTION) if not isRememberPwd: self.__rememberPwd = False password = '' elif len(password) > 0 and self.REMEMBER_PWD_TAG not in ds.keys(): self.__rememberPwd = True else: self.__rememberPwd = ds.readBool(self.REMEMBER_PWD_TAG, False) if self.__rememberPwd and decrypt is not None: try: password = decrypt(password) except (TypeError, AttributeError): LOG_CURRENT_EXCEPTION() if self.TOKEN2_TAG in ds.keys(): token2 = BigWorld.wg_ucpdata(ds.readString(self.TOKEN2_TAG)) if len(token2): separatorPos = token2.find(':') if separatorPos > 0: try: self.__passLength = int(token2[:separatorPos]) except ValueError: self.__passLength = self.DEFAULT_PASS_LENGTH self.__passLength = min(self.__passLength, _PASSWORD_MAX_LENGTH) self.__token2 = token2[separatorPos + 1:] password = '******' * self.__passLength else: self.__token2 = '' self.onConfigLoaded(self.__user, password, self.__rememberPwd, isRememberPwd)
def __handleConnectionStatus(self, stage, status, serverMsg, isAutoRegister): if self.__onLoggingTryingEndHdlr: self.__onLoggingTryingEndHdlr() STATUS_LOGGED_ON = 'LOGGED_ON' LOG_DEBUG('__handleConnectionStatus %s %s %s' % (stage, status, isAutoRegister)) if stage == 1: if status == STATUS_LOGGED_ON: handlerFunc = self.__logOnSuccess[status] elif isAutoRegister: handlerFunc = self.__logAutoRegisterHandlers.get( status, self.__logOnFailedDefaultHandler) if status == 'DNS_LOOKUP_FAILED': self.onLoginAppFailed(status, serverMsg) else: handlerFunc = self.__logOnFailedHandlers.get( status, self.__logOnFailedDefaultHandler) if status != 'LOGIN_REJECTED_LOGIN_QUEUE': self.__clearAutoLoginTimer() if status != 'LOGIN_REJECTED_RATE_LIMITED': self.__resetLgTimeout() self.onCancelQueue(False, False) g_preDefinedHosts.clearPeripheryTL() try: getattr(self, handlerFunc)(status, serverMsg) except: LOG_ERROR( 'Handle logon status error: status = %r, message = %r' % (status, serverMsg)) LOG_CURRENT_EXCEPTION() Waiting.hide('login') if connectionManager.isUpdateClientSoftwareNeeded(): self.onHandleUpdateClientSoftwareNeeded() elif status != STATUS_LOGGED_ON: connectionManager.disconnect() elif stage == 6: if not self.__kickedFromServer: self.onCancelQueue(False, False) msg = MENU.LOGIN_STATUS_DISCONNECTED if self.__accNotReady: msg = MENU.LOGIN_STATUS_ACCOUNTNOTREADY self.__accNotReady = False self.onSetStatus(i18n.convert(i18n.makeString(msg)), self.ALL_VALID) connectionManager.disconnect()
def __onStreamComplete(self, callback, resultsSubUrl, isSuccess, data): self.__waiting = False try: isSelfResults = resultsSubUrl is None battleResults = cPickle.loads(zlib.decompress(data)) folderName = self.__account.name if isSelfResults else resultsSubUrl save(folderName, battleResults) if callback is not None: callback(AccountCommands.RES_STREAM, convertToFullForm(battleResults)) if isSelfResults: self.__account.base.doCmdInt3(AccountCommands.REQUEST_ID_NO_RESPONSE, AccountCommands.CMD_BATTLE_RESULTS_RECEIVED, battleResults[0], 0, 0) except Exception: LOG_CURRENT_EXCEPTION() if callback is not None: callback(AccountCommands.RES_FAILURE, None) return
def readPeripheryTL(self): if not AUTO_LOGIN_QUERY_ENABLED: return (0, 0) result = (0, 0) try: loginSec = Settings.g_instance.userPrefs[Settings.KEY_LOGIN_INFO] if loginSec is not None: value = loginSec.readString('peripheryLifeTime') if len(value): value = pickle.loads(base64.b64decode(value)) if len(value) > 1: result = value except Exception: result = ('', 0) LOG_CURRENT_EXCEPTION() return result
def __onTokenReceived(self, requestID, tokenType, data): if self.__requestID != requestID or tokenType != self.__tokenType: return else: repository = _getAccountRepository() if repository: repository.onTokenReceived -= self.__onTokenReceived try: self.__lastResponse = self.__wrapper(**cPickle.loads(data)) except TypeError: LOG_CURRENT_EXCEPTION() self.__requestID = 0 if self.__callback is not None: self.__callback(self.__lastResponse) self.__callback = None return
def __makeReasonInfo(self, deathInfo): colors = deathInfo['colors'] if self.__isColorBlind: color = colors[1] else: color = colors[0] names = {'device': '', 'entity': '', 'killer': '', 'color': color} device = deathInfo['device'] if device: names['device'] = device reason = '' try: reason = deathInfo['text'] % names except TypeError: LOG_CURRENT_EXCEPTION() return reason
def getCarouselList(self, isReceived = False): result = [] for (block, record), value in self.getRecords().iteritems(): try: if _isAchievement(block): if block == ACHIEVEMENT_BLOCK.RARE: continue achievement = _getAchievement(block, record, value) result.append({'imgSource': achievement.getSmallIcon(), 'isSpecial': True, 'specialAlias': TOOLTIPS_CONSTANTS.BATTLE_STATS_ACHIEVS, 'specialArgs': [block, record, value]}) except Exception: LOG_ERROR('There is error while getting bonus dossier record name') LOG_CURRENT_EXCEPTION() return result
def start(self): for blockID in CONFIG_INTERFACE.BLOCK_IDS: if blockID in self.inited: continue try: self.vxSettingsApi.addMod( MOD_NAME, blockID, lambda *args: self.getTemplate(blockID), dict(), lambda *args: None, button_handler=self.onButtonPress) except Exception as err: logWarning('ConfigInterface startLoad {}'.format(repr(err))) LOG_CURRENT_EXCEPTION() else: self.inited.add(blockID)
def root_generator(filePath): """ Uses: with root_generator(path) as (ctx, section): <to read subsections> """ try: ctx, section = getRoot(filePath) except ResourceError as error: raise error else: try: yield (ctx, section) except: LOG_CURRENT_EXCEPTION() finally: ResMgr.purge(filePath, True)
def __playCaptureSound(self, playerTeam, baseTeam): if baseTeam not in self.__sounds: if playerTeam ^ baseTeam: soundID = _BASE_CAPTURE_SOUND_NAME_ENEMY else: soundID = _BASE_CAPTURE_SOUND_NAME_ALLY try: sound = self.__sounds.get(baseTeam, None) if sound is not None: sound.stop() sound = SoundGroups.g_instance.getSound2D(soundID) sound.play() self.__sounds[baseTeam] = sound except Exception: LOG_CURRENT_EXCEPTION() return
def _changeNext2Unlock(self, nodeCD, unlockProps, unlockStats): state = NODE_STATE.NEXT_2_UNLOCK totalXP = self._getAllPossibleXP(unlockProps.parentID, unlockStats) if totalXP >= unlockProps.xpCost: state = NODE_STATE.addIfNot(state, NODE_STATE.ENOUGH_XP) else: state = NODE_STATE.removeIfHas(state, NODE_STATE.ENOUGH_XP) if self.getItem(nodeCD).isElite: state = NODE_STATE.addIfNot(state, NODE_STATE.ELITE) try: data = self._nodes[self._nodesIdx[nodeCD]] data['state'] = state data['unlockProps'] = unlockProps except KeyError: LOG_CURRENT_EXCEPTION() return state
def onResultsSet(self, pickledBrowserResultsList): browserResultsList = cPickle.loads(pickledBrowserResultsList) LOG_DEBUG('unitBrowser.onResultsSet: %s' % browserResultsList) self.results.clear() for row in browserResultsList: try: cfdUnitID, unitMgrID, cmdrRating, peripheryID, strUnitPack = row unit = ClientUnit(packedUnit=strUnitPack) self.results[cfdUnitID] = dict(unitMgrID=unitMgrID, cmdrRating=cmdrRating, peripheryID=peripheryID, unit=unit) except: LOG_CURRENT_EXCEPTION() LOG_DEBUG('unitBrowser results=%r' % self.results) self.onResultsReceived(self.results)
def __updatePing(self, pingData, state=None): self.__lastUpdateTime = time.time() for rKey, pData in self.__pingResult.iteritems(): self.__pingResult[rKey] = PingData(pData.value, PING_STATUSES.UNDEFINED) try: for periphery, pingValue in pingData: self.__pingResult[periphery] = PingData( pingValue, state if state is not None else _getPingStatus(pingValue)) except Exception: LOG_CURRENT_EXCEPTION() self.__pingPerformedCallback(self.__pingResult) return