Ejemplo n.º 1
0
def _convertEULASetting(settings, item):
    value = item.value
    if 'full' in value:
        value['full'] = getClientLanguage() in value['full']
    else:
        value['full'] = False
    return settings._replace(**item.value)
Ejemplo n.º 2
0
    def connect(
        self,
        url,
        login,
        password,
        publicKeyPath=None,
        nickName=None,
        token2="",
        isNeedSavingPwd=False,
        tokenLoginParams=None,
    ):
        self.disconnect()
        self.__isVersionsDiffered = False
        self.__setConnectionStatus(CONNECTION_STATUS.connectionInProgress)
        basicLoginParams = {"login": login, "auth_method": AUTH_METHODS.BASIC}
        loginParams = tokenLoginParams if tokenLoginParams is not None else basicLoginParams
        loginParams["session"] = md5hex(getHardwareID())
        loginParams["auth_realm"] = constants.AUTH_REALM
        loginParams["game"] = "wot"
        loginParams["temporary"] = str(int(not isNeedSavingPwd))
        if nickName is not None:
            loginParams["nickname"] = nickName
            loginParams["auto_registration"] = "true"
        if constants.IS_IGR_ENABLED:
            loginParams["is_igr"] = "1"
        if token2:
            loginParams["token2"] = token2
            loginParams["auth_method"] = AUTH_METHODS.TOKEN2
        LOG_NOTE("User authentication method: {0}".format(loginParams["auth_method"]))
        clientContext = {"lang_id": getClientLanguage()}

        class LoginInfo:
            pass

        loginInfo = LoginInfo()
        loginInfo.username = json.dumps(loginParams).encode("utf8")
        loginInfo.password = password
        loginInfo.clientContext = json.dumps(clientContext)
        loginInfo.inactivityTimeout = constants.CLIENT_INACTIVITY_TIMEOUT
        if publicKeyPath is not None:
            loginInfo.publicKeyPath = publicKeyPath
        if login and constants.IS_DEVELOPMENT and login[0] == "@":
            try:
                loginInfo.username = login[1:]
            except IndexError:
                loginInfo.username = login

        BigWorld.connect(url, loginInfo, partial(self.connectionWatcher, nickName is not None))
        self.__setConnectionStatus(CONNECTION_STATUS.connectionInProgress)
        self.__loginName = login
        if g_preDefinedHosts.predefined(url) or g_preDefinedHosts.roaming(url):
            self.__host = g_preDefinedHosts.byUrl(url)
        else:
            for server in BigWorld.serverDiscovery.servers:
                if server.serverString == url:
                    self.__host = self.__host._replace(name=server.ownerName)
                    break

        return
 def request(self, listOfIds):
     LOG_DEBUG('Request action achievements data')
     if not len(listOfIds):
         return
     landId = getClientLanguage()
     for achieveId in listOfIds:
         getRareAchievementText(landId, achieveId, self.__onTextReceived)
         getRareAchievementImage(achieveId, self.__onImageReceived)
Ejemplo n.º 4
0
def getLanguageCode(args = None):
    """
    Gets client language code. Macros is $LANGUAGE_CODE.
    @return: string containing language code (2-5 chars). Note: replaces "_"
    to "-" if code has format xx_xx.
    """
    code = getClientLanguage()
    return code.replace('_', '-')
Ejemplo n.º 5
0
 def isShowLanguageBar(self):
     """
     @return: <bool> show laguage bar or not
     """
     try:
         return getClientLanguage() in self.language_bar
     except Exception:
         LOG_CURRENT_EXCEPTION()
         return False
Ejemplo n.º 6
0
 def audioTrack(self):
     """
     Returns number of audio track by language code. If track not found than
     returns 0.
     @return: number of audio track.
     """
     audio = self.__setting['audio']
     code = getClientLanguage()
     if code in audio:
         return audio[code]
     return 0
Ejemplo n.º 7
0
 def execute(self, section, processor, result):
     name = section['name'].asWideString if section.has_key('name') else section.asWideString
     if section.has_key('url'):
         if section['url'].asWideString == '#eulaUrl':
             lng = getClientLanguage()
             url = GUI_SETTINGS.eula.url.format(lng)
         else:
             url = section['url'].asWideString
     else:
         url = section.asWideString
     result.append(self._template % (url, name))
Ejemplo n.º 8
0
 def subtitleTrack(self):
     """
     Returns number of subtitle by language code. If track not found than
     returns 0.
     Note: subtitle track 0 turns subtitles off.
     @return: number of subtitle track.
     """
     subtitles = self.__setting['subtitles']
     code = getClientLanguage()
     if code in subtitles:
         return subtitles[code]
     return 0
 def request(self, listOfIds):
     LOG_DEBUG('Request action achievements data', listOfIds)
     if not len(listOfIds):
         return
     landId = getClientLanguage()
     for achieveId in listOfIds:
         if self.isLocallyLoaded(achieveId):
             LOG_DEBUG('Action achievements data loaded locally', achieveId)
             continue
         getRareAchievementText(landId, achieveId, self.__onTextReceived)
         getRareAchievementImage(achieveId, partial(self.__onImageReceived, IMAGE_TYPE.IT_67X71))
         getRareAchievementImageBig(achieveId, partial(self.__onImageReceived, IMAGE_TYPE.IT_180X180))
Ejemplo n.º 10
0
 def onAccountShowGUI(self, ctx = None):
     if ctx is None:
         ctx = {}
     if self.__currentLanguage is None:
         from helpers import getClientLanguage
         self.__currentLanguage = getClientLanguage()
         BigWorld.player().setLanguage(self.__currentLanguage)
     cursorMgr = self.window.cursorMgr
     if cursorMgr is not None:
         cursorMgr.attachCursor(True)
     else:
         Cursor.setAutoShow(True)
     self.window.fireEvent(ShowViewEvent(ShowViewEvent.SHOW_LOBBY, ctx))
     return
Ejemplo n.º 11
0
def getPrebattleLocalizedData(extraData = None):
    led = {}
    if extraData is None:
        extraData = getPrebattleSettings()['extraData']
    if extraData:
        from helpers import getClientLanguage
        lng = getClientLanguage()
        ld = extraData.get('localized_data', {})
        if ld:
            if lng in ld:
                led = ld[lng]
            elif DEFAULT_LANGUAGE in ld:
                led = ld[DEFAULT_LANGUAGE]
            else:
                sortedItems = ld.items()
                sortedItems.sort()
                led = sortedItems[0][1]
    return led
Ejemplo n.º 12
0
def getPrebattleLocalizedData(extraData=None):
    led = {}
    if extraData is None:
        extraData = getPrebattleSettings()['extraData']
    if extraData:
        from helpers import getClientLanguage
        lng = getClientLanguage()
        ld = extraData.get('localized_data', {})
        if ld:
            if lng in ld:
                led = ld[lng]
            elif DEFAULT_LANGUAGE in ld:
                led = ld[DEFAULT_LANGUAGE]
            else:
                sortedItems = ld.items()
                sortedItems.sort()
                led = sortedItems[0][1]
        else:
            return extraData.get('descr', {})
    return led
Ejemplo n.º 13
0
 def analytics_start(self):
     from helpers import getClientLanguage
     self.lang = str(getClientLanguage()).upper()
     template = self.template()
     requestsPool = []
     if not self.analytics_started:
         requestsPool.append(dict(template, sc='start', t='screenview'))
         requestsPool.extend(
             dict(
                 template, ec='config', ea='collect', el=conf.split('.')[0])
             for conf in self.confList)
         self.analytics_started = True
         self.old_user = BigWorld.player().databaseID
         self.old_playerName = BigWorld.player().name
     elif BigWorld.time() - self.lastTime >= 1200:
         requestsPool.append(dict(template, ec='session', ea='keep'))
     for params in requestsPool:
         self.lastTime = BigWorld.time()
         urllib2.urlopen(url='https://www.google-analytics.com/collect?',
                         data=urllib.urlencode(params)).read()
Ejemplo n.º 14
0
 def __init__(self, ID, modsGroup):
     self.modsGroup = modsGroup
     self.ID = ID
     self.langPath = ''
     self.iconPath = 'scripts/client/%s.png' % self.ID
     self.lang = DEFAULT_LANGUAGE
     self.i18n = {}
     self.onMSAPopulate = Event.Event()
     self.onMSADestroy = Event.Event()
     self.isMSAWindowOpen = False
     self.MSAHandlers = {}
     self.init()
     try:
         from helpers import getClientLanguage
         newLang = str(getClientLanguage()).lower()
         if newLang != self.lang:
             self.lang = newLang
     except StandardError:
         traceback.print_exc()
     self.loadLang()
Ejemplo n.º 15
0
def registerSettings(config, mode='full'):
    """
    Register a settings block in this mod's settings window.
    """
    try:
        from helpers import getClientLanguage
        newLang = str(getClientLanguage()).lower()
        if newLang != config.lang:
            config.lang = newLang
            config.loadLang()
    except StandardError:
        traceback.print_exc()
    try:
        # noinspection PyUnresolvedReferences
        from gui.vxSettingsApi import vxSettingsApi
        if config.modSettingsID not in modSettingsContainers:
            modSettingsContainers[
                config.modSettingsID] = config.containerClass(
                    config.modSettingsID, config.configPath)
        msc = modSettingsContainers[config.modSettingsID]
        msc.onMSAPopulate += config.onMSAPopulate
        msc.onMSADestroy += config.onMSADestroy
        vxSettingsApi.onDataChanged += config.onDataChanged
        if mode == 'block':
            for blockID in config.blockIDs:
                vxSettingsApi.addMod(config.modSettingsID, config.ID + blockID,
                                     partial(config.createTemplate, blockID),
                                     config.getDataBlock(blockID),
                                     partial(config.onApplySettings, blockID),
                                     config.onButtonPress)
        else:
            vxSettingsApi.addMod(config.modSettingsID,
                                 config.ID, config.createTemplate,
                                 config.getData(), config.onApplySettings,
                                 config.onButtonPress)
    except ImportError:
        print '%s: no-GUI mode activated' % config.ID
    except StandardError:
        traceback.print_exc()
Ejemplo n.º 16
0
def registerSettings(config):
    """
    Register a settings block in this mod's settings window.
    """
    try:
        from helpers import getClientLanguage
        newLang = str(getClientLanguage()).lower()
        if newLang != config.lang:
            config.lang = newLang
            config.loadLang()
    except StandardError:
        traceback.print_exc()
    if MSA_Orig is None:
        print config.ID + ': no-GUI mode activated'
        return
    if config.modSettingsID not in config.modSettingsContainers:
        c = config.modSettingsContainers[
            config.modSettingsID] = config.containerClass(
                config.modSettingsID, config.modsGroup)
        c.API = ModsSettings(config.modSettingsID, c)
    msc = config.modSettingsContainers[config.modSettingsID]
    msc.onMSAPopulate += config.onMSAPopulate
    msc.onMSADestroy += config.onMSADestroy
    if hasattr(config, 'blockIDs'):
        for ID in config.blockIDs:
            msc.MSAHandlers[config.ID + ID] = {
                'apply': partial(config.onApplySettings, blockID=ID),
                'button': partial(config.onButtonPress, blockID=ID)
            }
            msc.API.setModTemplate(config.ID + ID, config.template[ID],
                                   msc.MSAApply, msc.MSAButton)
    else:
        msc.MSAHandlers[config.ID] = {
            'apply': config.onApplySettings,
            'button': config.onButtonPress
        }
        msc.API.setModTemplate(config.ID, config.template, msc.MSAApply,
                               msc.MSAButton)
Ejemplo n.º 17
0
def weave(weaver, stateInGarage):
    weaver.weave(pointcut=_PointcutPrbDisableEntitySelect)
    weaver.weave(pointcut=_PointcutPrbInvitationText)
    weaver.weave(pointcut=_PointcutPrbDisableAcceptButton)
    weaver.weave(pointcut=_PointcutSysMessagesClient, avoid=True)
    weaver.weave(pointcut=_PointcutSysMessagesServer, avoid=True)
    weaver.weave(pointcut=_PointcutUnreadMessages)
    weaver.weave(pointcut=_PointcutFriendRequest, avoid=True)
    weaver.weave(pointcut=_PointcutShowModuleInfo, avoid=True)
    from bootcamp.Bootcamp import g_bootcamp
    if not g_bootcamp.isResearchFreeLesson():
        weaver.weave(pointcut=_PointcutNoFittingPopover, avoid=True)
        weaver.weave(pointcut=_PointcutDisableModuleClickSound)
    weaver.weave(pointcut=_PointcutOnOptionalDeviceSelectPopoverGetTabData)
    weaver.weave(
        pointcut=_PointcutOnOptionalDeviceSelectPopoverGetInitialTabIndex)
    weaver.weave(
        pointcut=_PointcutOnOptionalDeviceSelectPopoverPreventCloseAfterMessage
    )
    weaver.weave(pointcut=_PointcutOverrideAOGASMessageTimeout)
    if getClientLanguage() == 'ko':
        weaver.weave(pointcut=_PointcutOverrideKoreaParentalControl)
    weaver.weave(pointcut=_PointcutDisableRankedBattleEvents)
Ejemplo n.º 18
0
 def __setConnectionData(self, params, password):
     self.__lastLoginName = params['login']
     self.__connectionMethod = params['auth_method']
     params['auth_realm'] = constants.AUTH_REALM
     m = hashlib.md5()
     m.update(params['session'])
     params['session'] = m.hexdigest()
     if constants.IS_IGR_ENABLED:
         params['is_igr'] = '1'
     username_ = json.dumps(params, encoding='utf-8')
     LOG_NOTE('User authentication method: {0}'.format(params['auth_method']))
     if 'token2' in params and params['token2']:
         password = ''
     else:
         password = pwd_token.generate(password)
     self.__connectionData.username = username_
     self.__connectionData.password = password
     self.__connectionData.inactivityTimeout = constants.CLIENT_INACTIVITY_TIMEOUT
     self.__connectionData.clientContext = json.dumps({'lang_id': getClientLanguage()})
     if constants.IS_DEVELOPMENT and params['auth_method'] == CONNECTION_METHOD.BASIC and params['login'][0] == '@':
         try:
             self.__connectionData.username = params['login'][1:]
         except IndexError:
             self.__connectionData.username = params['login']
Ejemplo n.º 19
0
 def __gameSession_onClientNotify(self, sessionDuration, timeTillMidnight, playTimeLeft):
     LOG_DEBUG('onGameSessionNotification', sessionDuration, timeTillMidnight, playTimeLeft)
     if getClientLanguage() == 'ko':
         key = '#system_messages:gameSessionControl/korea/{0:>s}'
         msgList = [i18n.makeString(key.format('sessionTime'), sessionTime=time.strftime('%H:%M', time.gmtime(sessionDuration))), i18n.makeString(key.format('note'))]
         self.proto.serviceChannel.pushClientSysMessage('\n'.join(msgList), SM_TYPE.Warning)
Ejemplo n.º 20
0
 def isTwelveHoursFormat(self):
     return getClientLanguage() == 'en'
Ejemplo n.º 21
0
def getShopProductInfo(productID, callback=None, webCtrl=None):
    productInfo = None
    accessTokenData = yield webCtrl.getAccessTokenData(force=False)
    loginUrl = yield URLMacros().parse(url=getLoginUrl())
    productUrl = yield URLMacros().parse(url=getProductsUrl(productID))
    reqTimeoutSeconds = 10.0
    if accessTokenData is not None and loginUrl and productUrl:
        authHeader = ('Authorization: Basic {}'.format(str(accessTokenData.accessToken)),)
        authResponse = yield _fetchUrl(loginUrl, authHeader, reqTimeoutSeconds, 'POST')
        if 200 <= authResponse.responseCode < 300:
            getProductHeader = authHeader + ('Cookie: {}'.format(authResponse.headers().get('Set-Cookie')), 'Accept-Language: {}'.format(getClientLanguage()))
            productResponse = yield _fetchUrl(productUrl, getProductHeader, reqTimeoutSeconds, 'GET')
            productInfo = _tryParseProductInfo(productResponse.body)
    if callback:
        callback(productInfo)
    return
Ejemplo n.º 22
0
def getVehCD(vehicleID):
    return BigWorld.player().arena.vehicles[vehicleID]['vehicleType'].type.compactDescr


# Region and language

GAME_REGION = 'null'
_url = ResMgr.openSection('scripts_config.xml').readString('csisUrl')
if _url is not None:
    if 'csis-ct.worldoftanks.' in _url:
        GAME_REGION = 'CT'
    elif 'worldoftanks.ru' in _url:
        GAME_REGION = 'RU'
    elif 'worldoftanks.eu' in _url:
        GAME_REGION = 'EU'
    elif 'worldoftanks.com' in _url:
        GAME_REGION = 'NA'
    elif 'worldoftanks.asia' in _url:
        GAME_REGION = 'ASIA'
    elif 'worldoftanks.kr' in _url:
        GAME_REGION = 'KR'
    elif 'worldoftanks.cn' in _url:
        GAME_REGION = 'CN'
if GAME_REGION == 'null':
    _url = ResMgr.openSection('scripts_config.xml').readString('login/host/name')
    if 'Supertest' in _url:
        GAME_REGION = 'ST'

from helpers import getClientLanguage
GAME_LANGUAGE = getClientLanguage()
Ejemplo n.º 23
0
 def readEULA(dataSection):
     return EULAProps(
         getClientLanguage()
         in GuiSettings.readStringsList(dataSection['full']),
         dataSection.readString('url'))
Ejemplo n.º 24
0
class OfferGift(object):
    _langCode = getClientLanguage()

    def __init__(self, giftID, giftData):
        self._id = giftID
        self._data = giftData
        self._bonus = None
        self._bonuses = None
        return

    @property
    def id(self):
        return self._id

    @property
    def cdnLocFilePath(self):
        _path = self._data.get(CDN_KEY, {}).get('localization')
        return _path % self._langCode if _path else ''

    @property
    def cdnImagePath(self):
        return self._data.get(CDN_KEY, {}).get('image', '')

    @property
    def cdnIconPath(self):
        return self._data.get(CDN_KEY, {}).get('icon', '')

    @property
    def fromCdn(self):
        return CDN_KEY in self._data

    @property
    def title(self):
        return self.bonus.getOfferName(
        ) if not self.fromCdn and self.bonus else ''

    @property
    def description(self):
        if not self.fromCdn and self.bonus:
            description = self.bonus.getOfferDescription()
            separator = ''
            itemsInfo = ''
            if self.isVehicle:
                items = None
                if self.bonus.isWithCrew and self.isWithSlotBonus:
                    items = R.strings.offers.giftDescription.tank.withCrewAndSlot(
                    )
                elif self.bonus.isWithCrew:
                    items = R.strings.offers.giftDescription.tank.withCrew()
                elif self.isWithSlotBonus:
                    items = R.strings.offers.giftDescription.tank.withSlot()
                if items is not None:
                    itemsInfo = backport.text(
                        R.strings.offers.giftDescription.tank.base(),
                        items=backport.text(items))
                if description and itemsInfo:
                    separator = ' ' if description.endswith('.') else '. '
            return ''.join([description, separator, itemsInfo])
        else:
            return ''

    @property
    def icon(self):
        return getGfImagePath(self.bonus.getOfferIcon()
                              ) if not self.fromCdn and self.bonus else ''

    @property
    def price(self):
        return self._data.get('price', 1)

    def limit(self):
        return self._data.get('limit', 1)

    @property
    def nationFlag(self):
        flag = None
        if not self.fromCdn and self.bonus:
            flag = self.bonus.getOfferNationalFlag()
        return flag or ''

    @property
    def highlight(self):
        return self.bonus.getOfferHighlight(
        ) if not self.fromCdn and self.bonus else ''

    @property
    def giftCount(self):
        return self.bonus.getGiftCount() if self.bonus else 0

    @property
    def inventoryCount(self):
        return self.bonus.getInventoryCount() if self.bonus else 0

    @property
    def rentType(self):
        if self.bonus and self.isVehicle:
            _, vInfo = self.bonus.getVehicles()[0]
            rentType, _ = self.bonus.getRentInfo(vInfo)
            return rentType
        return RentType.NO_RENT

    @property
    def rentValue(self):
        if self.bonus and self.isVehicle:
            _, vInfo = self.bonus.getVehicles()[0]
            _, rentValue = self.bonus.getRentInfo(vInfo)
            return rentValue

    @property
    def isDisabled(self):
        disabled = True
        if self.bonuses:
            disabled = any(
                (bonus.isMaxCountExceeded() for bonus in self.bonuses))
        return disabled

    @property
    def bonuses(self):
        if self._bonuses is None:
            self._bonuses = []
            for name, value in self._data.get('bonus', dict()).iteritems():
                self._bonuses += getOfferBonuses(name, value)

            if not self._bonuses:
                if not self.fromCdn:
                    _logger.error(
                        'Wrong gift id=%d. For representation must be at least one valid bonus or cdn section. bonus=%s',
                        self.id, self._data)
            else:
                self._bonuses.sort(key=lambda x: OFFER_BONUSES_PRIORITY.index(
                    x.getName()) if x.getName() in OFFER_BONUSES_PRIORITY else
                                   DEFAULT_PRIORITY)
        return self._bonuses

    @property
    def bonus(self):
        if self._bonus is None:
            for bonus in self.bonuses:
                if bonus.canBeShown():
                    self._bonus = bonus
                    break

        return self._bonus

    @property
    def isWithSlotBonus(self):
        return 'slots' in self._data.get('bonus', dict())

    @property
    def buttonLabel(self):
        return R.strings.offers.giftsWindow.previewButtonLabel(
        ) if self.isVehicle else R.strings.offers.giftsWindow.takeButtonLabel(
        )

    @property
    def isVehicle(self):
        return isinstance(self.bonus, VehiclesBonus)

    @property
    def bonusType(self):
        return self.bonus.getName() if self.bonus else None
Ejemplo n.º 25
0
 def isShowLanguageBar(self):
     try:
         return getClientLanguage() in self.language_bar
     except Exception:
         LOG_CURRENT_EXCEPTION()
         return False
from debug_utils import LOG_ERROR
from helpers import getClientLanguage
from gui.Scaleform.daapi.view.lobby.messengerBar.VehicleCompareCartButton import VehicleCompareCartButton
from gui.Scaleform.daapi.view.meta.MessengerBarMeta import MessengerBarMeta

import xvm_main.python.utils as utils
from xfw.events import registerEvent
from xfw_actionscript.python import as_event, as_callback

#####################################################################
# constants

buttonsState = None
countVehicles = None

if getClientLanguage() == 'ru':
    url = 'https://stats.modxvm.com/ru/stat/players/'
else:
    url = 'https://stats.modxvm.com/en/stat/players/'

#####################################################################
# handlers


def _stats_down(data):
    if data['buttonIdx'] == 0:
        accountDBID = utils.getAccountDBID()
        try:
            BigWorld.wg_openWebBrowser(url + str(accountDBID))
        except Exception:
            LOG_ERROR(
Ejemplo n.º 27
0
 def getDescriptionUrl(self):
     histNote = self._data.get("urls", {}).get("histNote")
     if histNote is not None:
         return histNote % {"langID": getClientLanguage()}
     else:
         return
Ejemplo n.º 28
0
 def readEULA(dataSection):
     return EULAProps(getClientLanguage() in GuiSettings.readStringsList(dataSection['full']), dataSection.readString('url'))
Ejemplo n.º 29
0

from constants import DEFAULT_LANGUAGE
from helpers import getClientLanguage

from gui.modsListApi.modslist_constants import DEFAULT_UI_LANGUAGE, LANGUAGE_CODES, LANGUAGE_FILE_PATH
from gui.modsListApi.utils import parseLangFields

__all__ = ('l10n', )

_LANGUAGES = {}

for langCode in LANGUAGE_CODES:
	_LANGUAGES[langCode] = parseLangFields(LANGUAGE_FILE_PATH % langCode)

_CLIENT_LANGUAGE = getClientLanguage()
if _CLIENT_LANGUAGE in _LANGUAGES.keys():
	_LANGUAGE = _LANGUAGES[_CLIENT_LANGUAGE]
elif DEFAULT_LANGUAGE in _LANGUAGES.keys():
	_LANGUAGE = _LANGUAGES[DEFAULT_LANGUAGE]
else:
	_LANGUAGE = _LANGUAGES[DEFAULT_UI_LANGUAGE]

def l10n(key):
	"""returns localized value relative to key"""
	result = key
	if key in _LANGUAGE:
		result = _LANGUAGE[key]
	elif key in _LANGUAGES[DEFAULT_UI_LANGUAGE]:
		result = _LANGUAGES[DEFAULT_UI_LANGUAGE][key]
	return result
Ejemplo n.º 30
0
class OfferEventData(object):
    __slots__ = ('_id', '_data', '_langCode')
    _itemsCache = dependency.descriptor(IItemsCache)
    _offersProvider = dependency.descriptor(IOffersDataProvider)
    _langCode = getClientLanguage()

    def __init__(self, itemID, data):
        self._id = itemID
        self._data = dict(data)

    @property
    def id(self):
        return self._id

    @property
    def token(self):
        return self._data.get('token')

    @property
    def giftToken(self):
        return self._data.get('giftToken')

    @property
    def showBanner(self):
        return self._data.get('showBanner')

    @property
    def priority(self):
        return self._data.get('priority')

    @property
    def showPrice(self):
        return self._data.get('showPrice', False)

    @property
    def showInGUI(self):
        return self._data.get('showInGUI')

    @property
    def cdnLocFilePath(self):
        _path = self._data.get(CDN_KEY, {}).get('localization')
        return _path % self._langCode if _path else ''

    @property
    def cdnBannerLogoPath(self):
        return self._data.get(CDN_KEY, {}).get('bannerLogo', '')

    @property
    def cdnLogoPath(self):
        return self._data.get(CDN_KEY, {}).get('logo', '')

    @property
    def cdnGiftsBackgroundPath(self):
        return self._data.get(CDN_KEY, {}).get('giftsBackground', '')

    @property
    def cdnGiftsTokenImgPath(self):
        return self._data.get(CDN_KEY, {}).get('giftTokenImg', '')

    @property
    def availableGifts(self):
        received = self._receivedGifts
        if received is None:
            return []
        else:
            return [
                OfferGift(giftID, settings)
                for giftID, settings in self._data.get('gift', {}).iteritems()
                if giftID not in received or not settings.get('limit', 1)
                or giftID in received and settings.get('limit', 1)
                and received[giftID] < settings.get('limit', 1)
            ]

    def getGift(self, giftID):
        giftsData = self._data.get('gift')
        return OfferGift(giftID, self._data['gift'][giftID]
                         ) if giftsData and giftID in giftsData else None

    def getGiftAvailabelCount(self, giftID):
        received = self._receivedGifts
        if received is None:
            return 0
        else:
            giftsData = self._data.get('gift')
            if giftsData and giftID in giftsData:
                limits = giftsData[giftID].get('limit', 1)
                if limits > 0:
                    if giftID not in received:
                        return limits
                    return limits - received[giftID]
            return -1

    def getAllGifts(self):
        return [
            OfferGift(giftID, settings)
            for giftID, settings in self._data.get('gift', {}).iteritems()
        ]

    @property
    def clicksCount(self):
        return min(self.availableTokens, self.availableGiftsCount)

    @property
    def availableTokens(self):
        return self._tokensCache.getTokenCount(self.giftToken)

    @property
    def availableGiftsCount(self):
        received = self._receivedGifts
        if received is None:
            return 0
        else:
            giftsCount = len(self._data.get('gift', {}))
            notReceived = giftsCount - len(self.isOutOfLimit)
            return max(notReceived, 0)

    @property
    def isOutOfLimit(self):
        received = self._receivedGifts
        if received is None:
            return []
        else:
            outOfLimits = []
            gifts = self._data.get('gift', {})
            for giftID in received:
                limit = gifts.get(giftID, {}).get('limit', 1)
                if limit and received[giftID] >= limit:
                    outOfLimits.append(giftID)

            return outOfLimits

    @property
    def expiration(self):
        return min(self._tokensCache.getTokenExpiryTime(self.token),
                   self._tokensCache.getTokenExpiryTime(self.giftToken),
                   self.getFinishTime())

    @property
    def isOfferAvailable(self):
        return self._tokensCache.isTokenAvailable(
            self.token) and self._tokensCache.isTokenAvailable(
                self.giftToken) and not self.isOutOfDate and bool(
                    self.availableGiftsCount)

    @property
    def isOutOfDate(self):
        return self.getFinishTimeLeft() <= 0

    def getFinishTime(self):
        return time_utils.makeLocalServerTime(
            self._data['finishTime']
        ) if 'finishTime' in self._data else time.time()

    def getFinishTimeLeft(self):
        return time_utils.getTimeDeltaFromNowInLocal(self.getFinishTime())

    @property
    def _tokensCache(self):
        return self._itemsCache.items.tokens

    @property
    def _receivedGifts(self):
        return self._offersProvider.getReceivedGifts(self.id)
Ejemplo n.º 31
0
 def onConnected(self):
     if self.__currentLanguage is None:
         self.__currentLanguage = getClientLanguage()
         BigWorld.player().setLanguage(self.__currentLanguage)
     return
 def setBgPath(self):
     if getClientLanguage() in ('ru', 'be', 'uk', 'kk'):
         self.flashObject.as_setBgPath(RES_ICONS.MAPS_ICONS_AUTHORS_BG_RU)
     else:
         self.flashObject.as_setBgPath(RES_ICONS.MAPS_ICONS_AUTHORS_BG_EN)
Ejemplo n.º 33
0
 def getLanguageCode(self, args, callback):
     code = getClientLanguage()
     callback(code.replace('_', '-'))
Ejemplo n.º 34
0
 def __readEULAShort(self):
     return makeHtmlString('html_templates:lobby/dialogs', 'eula', {'eulaURL': GUI_SETTINGS.eula.url.format(getClientLanguage())})
Ejemplo n.º 35
0
 def init(self):
     super(_ClanWebState, self).init()
     clanProfile = self.lobbyContext.getServerSettings().clanProfile
     self.__webRequester = g_clanFactory.createWebRequester(clanProfile, client_lang=getClientLanguage())
     self.__gateUrl = clanProfile.getGateUrl()
     self.__requestsCtrl = g_clanFactory.createClanRequestsController(self._clanCtrl, g_clanFactory.createClanRequester(self.__webRequester))
Ejemplo n.º 36
0
 def __init__(self, offerID):
     settings = ViewSettings(layoutID=R.views.lobby.offers.OfferBannerWindow(), flags=ViewFlags.WINDOW_DECORATOR, model=OfferBannerModel())
     super(OfferBannerWindowView, self).__init__(settings)
     self._offerID = offerID
     self._langCode = getClientLanguage()
Ejemplo n.º 37
0
from helpers import getClientLanguage

lang = getClientLanguage().lower()


def getLocalization():
    if lang == "ru":
        from .ru import translate
    elif lang == "de":
        from .de import translate
    else:
        from .en import translate
    return translate


localization = getLocalization()
Ejemplo n.º 38
0
#############################
# Public

_updateurl = ResMgr.openSection('scripts_config.xml').readString('csisUrl')

if _updateurl is not None:
    if 'csis-ct.worldoftanks.' in _updateurl:
        region = 'CT'
    elif 'worldoftanks.ru' in _updateurl:
        region = 'RU'
    elif 'worldoftanks.eu' in _updateurl:
        region = 'EU'
    elif 'worldoftanks.com' in _updateurl:
        region = 'NA'
    elif 'worldoftanks.cn' in _updateurl:
        region = 'CN'
    elif 'worldoftanks.asia' in _updateurl:
        region = 'ASIA'
    elif 'worldoftanks.vn' in _updateurl:
        region = 'VTC'
    elif 'worldoftanks.kr' in _updateurl:
        region = 'KR'
    else:
        region = 'null'
else:
    region = 'null'

from helpers import getClientLanguage

language = getClientLanguage()
Ejemplo n.º 39
0
 def full(self):
     return getClientLanguage() in self.__full
Ejemplo n.º 40
0
 def getLanguageCode(self, args, callback):
     code = getClientLanguage()
     callback(code.replace('_', '-'))
Ejemplo n.º 41
0
        with open(ModSettingsAPI.MODSETTINGSPATH+modname+'.cfg', 'w') as outfile:
                json.dump(data, outfile, sort_keys=True, indent=4, separators=(',', ': '),ensure_ascii=True)
    except:
        print "[ModSettingsAPI] writeMod crashed at"+modname
        print sys.exc_info()[0]
        print sys.exc_info()[1]
        traceback.print_tb(sys.exc_info()[2])
        
    
    
#print sys.modules['gui.Scaleform.daapi.view.lobby.settings.SettingsWindow'] 
initHooks()

import ResMgr
a = ResMgr.openSection(VERSION_FILE_PATH).readString('version')
#     v.0.9.3 Common Test #30
a = a.split('#')[0][2:-1]
#print a
#ModSettingsAPI.WoTVersion = WoTVersion[2:-5]
ModSettingsAPI.WoTVersion = a
#print "[ModSettingsAPI] fetching updates for",ModSettingsAPI.WoTVersion

defset = {
    "FlashSettingsFile" : "ModSettingsPanel.swf",
    "language" : helpers.getClientLanguage(),
    "debugMode" : False
}
msa = ModSettingsAPI2(modname="ModSettings", authors="4lCapwn, CS2001",localversion="1.2.4", defaultsettings=defset,updateurl="http://mods.wot.tools/files/MSA/MSA.php",homeurl="http://forum.worldoftanks.eu/index.php?/topic/363138-092-modsettings-api-v115-beta-release-by-4lcapwn-and-cs2001/")
initPostHooks()

print "[ModSettings] initialized"
Ejemplo n.º 42
0
 def getLanguageCode(self, args, callback):
     code = getClientLanguage()
     callback(code.replace("_", "-"))
Ejemplo n.º 43
0
 def init(self):
     super(_ClanWebState, self).init()
     self.__webRequester = g_clanFactory.createWebRequester(g_lobbyContext.getServerSettings().clanProfile, client_lang=getClientLanguage())
     self.__requestsCtrl = g_clanFactory.createClanRequestsController(self._clanCtrl, g_clanFactory.createClanRequester(self.__webRequester))
Ejemplo n.º 44
0
 def __readEULAShort(self):
     return makeHtmlString(
         'html_templates:lobby/dialogs', 'eula',
         {'eulaURL': GUI_SETTINGS.eula.url.format(getClientLanguage())})
Ejemplo n.º 45
0

#print sys.modules['gui.Scaleform.daapi.view.lobby.settings.SettingsWindow']
initHooks()

import ResMgr
a = ResMgr.openSection(VERSION_FILE_PATH).readString('version')
#     v.0.9.3 Common Test #30
a = a.split('#')[0][2:-1]
#print a
#ModSettingsAPI.WoTVersion = WoTVersion[2:-5]
ModSettingsAPI.WoTVersion = a
#print "[ModSettingsAPI] fetching updates for",ModSettingsAPI.WoTVersion

defset = {
    "FlashSettingsFile": "ModSettingsPanel.swf",
    "language": helpers.getClientLanguage(),
    "debugMode": False
}
msa = ModSettingsAPI2(
    modname="ModSettings",
    authors="4lCapwn, CS2001",
    localversion="1.2.4",
    defaultsettings=defset,
    updateurl="http://mods.wot.tools/files/MSA/MSA.php",
    homeurl=
    "http://forum.worldoftanks.eu/index.php?/topic/363138-092-modsettings-api-v115-beta-release-by-4lcapwn-and-cs2001/"
)
initPostHooks()

print "[ModSettings] initialized"
Ejemplo n.º 46
0
 def isShowLanguageBar(self):
     try:
         return getClientLanguage() in self.language_bar
     except Exception as ex:
         _logger.exception(ex)
         return False
Ejemplo n.º 47
0
    def create(self):
        LOG_BROWSER('CREATE ', self.__baseUrl, self.__browserID)
        clientLanguage = helpers.getClientLanguage()
        self.__browser = BigWorld.createBrowser(self.__browserID,
                                                clientLanguage)
        if self.__browser is None:
            LOG_BROWSER('create() NO BROWSER WAS CREATED', self.__baseUrl)
            return
        else:
            self.__browser.script = EventListener(self)
            self.__browser.script.onLoadStart += self.__onLoadStart
            self.__browser.script.onLoadEnd += self.__onLoadEnd
            self.__browser.script.onLoadingStateChange += self.__onLoadingStateChange
            self.__browser.script.onDOMReady += self.__onReadyToShowContent
            self.__browser.script.onCursorUpdated += self.__onCursorUpdated
            self.__browser.script.onReady += self.__onReady

            def injectBrowserKeyEvent(me, e):
                if _BROWSER_KEY_LOGGING:
                    LOG_BROWSER('injectBrowserKeyEvent',
                                (e.key, e.isKeyDown(), e.isAltDown(),
                                 e.isShiftDown(), e.isCtrlDown()))
                me.__browser.injectKeyEvent(e)

            def injectKeyDown(me, e):
                injectBrowserKeyEvent(me, e)

            def injectKeyUp(me, e):
                injectBrowserKeyEvent(me, e)

            def resetBit(value, bitMask):
                return value & ~bitMask

            self.__browserKeyHandlers = (
                (Keys.KEY_LEFTARROW, True, True, None, None,
                 lambda me, _: me.__browser.goBack()),
                (Keys.KEY_RIGHTARROW, True, True, None, None,
                 lambda me, _: me.__browser.goForward()),
                (Keys.KEY_F5, True, None, None, None,
                 lambda me, _: me.__browser.reload()),
                (Keys.KEY_LSHIFT, False, None, True, None,
                 lambda me, e: injectKeyUp(
                     me,
                     BigWorld.KeyEvent(e.key, e.repeatCount,
                                       resetBit(e.modifiers, 1), None, e.
                                       cursorPosition))),
                (Keys.KEY_RSHIFT, False, None, True, None,
                 lambda me, e: injectKeyUp(
                     me,
                     BigWorld.KeyEvent(e.key, e.repeatCount,
                                       resetBit(e.modifiers, 1), None, e.
                                       cursorPosition))),
                (Keys.KEY_LCONTROL, False, None, None, True,
                 lambda me, e: injectKeyUp(
                     me,
                     BigWorld.KeyEvent(e.key, e.repeatCount,
                                       resetBit(e.modifiers, 2), None, e.
                                       cursorPosition))),
                (Keys.KEY_RCONTROL, False, None, None, True,
                 lambda me, e: injectKeyUp(
                     me,
                     BigWorld.KeyEvent(e.key, e.repeatCount,
                                       resetBit(e.modifiers, 2), None, e.
                                       cursorPosition))),
                (None, True, None, None, None,
                 lambda me, e: injectKeyDown(me, e)),
                (None, False, None, None, None,
                 lambda me, e: injectKeyUp(me, e)))
            return
 def onConnected(self):
     if GUI_SETTINGS.lookup('encyclopedia'):
         self.__baseUrl = GUI_SETTINGS.encyclopedia['url']
         self.__isSuitableLanguage = getClientLanguage(
         ) in GUI_SETTINGS.encyclopedia.get('languages', ())
Ejemplo n.º 49
0
 def getDescriptionUrl(self):
     histNote = self._data.get('urls', {}).get('histNote')
     if histNote is not None:
         return histNote % {'langID': getClientLanguage()}
Ejemplo n.º 50
0
 def getDescriptionUrl(self):
     histNote = self._data.get('urls', {}).get('histNote')
     if histNote is not None:
         return histNote % {'langID': getClientLanguage()}
Ejemplo n.º 51
0
 def isTwelveHoursFormat(self):
     return getClientLanguage() == 'en'
Ejemplo n.º 52
0
def getLanguageCode(args=None):
    code = getClientLanguage()
    return code.replace('_', '-')
Ejemplo n.º 53
0
#############################
# Public

_updateurl = ResMgr.openSection('scripts_config.xml').readString('csisUrl')

if _updateurl is not None:
    if 'csis-ct.worldoftanks.' in _updateurl:
        region = 'CT'
    elif 'worldoftanks.ru' in _updateurl:
        region = 'RU'
    elif 'worldoftanks.eu' in _updateurl:
        region = 'EU'
    elif 'worldoftanks.com' in _updateurl:
        region = 'NA'
    elif 'worldoftanks.cn' in _updateurl:
        region = 'CN'
    elif 'worldoftanks.asia' in _updateurl:
        region = 'SG'
    elif 'worldoftanks.vn' in _updateurl:
        region = 'VTC'
    elif 'worldoftanks.kr' in _updateurl:
        region = 'KR'
    else:
        region = 'null'
else:
    region = 'null'

from helpers import getClientLanguage
language = getClientLanguage()
Ejemplo n.º 54
0
 def onAccountBecomePlayer(self):
     if self.__currentLanguage is None:
         self.__currentLanguage = getClientLanguage()
         BigWorld.player().setLanguage(self.__currentLanguage)
     return
Ejemplo n.º 55
0
 def __readEULAShort(self):
     return makeHtmlString(
         "html_templates:lobby/dialogs", "eula", {"eulaURL": GUI_SETTINGS.eula.url.format(getClientLanguage())}
     )
Ejemplo n.º 56
0
    ).arena.vehicles[vehicleID]['vehicleType'].type.compactDescr


# Region and language

GAME_REGION = 'null'
_url = ResMgr.openSection('scripts_config.xml').readString('csisUrl')
if _url is not None:
    if 'csis-ct.worldoftanks.' in _url:
        GAME_REGION = 'CT'
    elif 'worldoftanks.ru' in _url:
        GAME_REGION = 'RU'
    elif 'worldoftanks.eu' in _url:
        GAME_REGION = 'EU'
    elif 'worldoftanks.com' in _url:
        GAME_REGION = 'NA'
    elif 'worldoftanks.asia' in _url:
        GAME_REGION = 'ASIA'
    elif 'worldoftanks.kr' in _url:
        GAME_REGION = 'KR'
    elif 'worldoftanks.cn' in _url:
        GAME_REGION = 'CN'
if GAME_REGION == 'null':
    _url = ResMgr.openSection('scripts_config.xml').readString(
        'login/host/name')
    if 'Supertest' in _url:
        GAME_REGION = 'ST'

from helpers import getClientLanguage
GAME_LANGUAGE = getClientLanguage()