class SocialWebApi(object):
    lobbyContext = dependency.descriptor(ILobbyContext)

    def __init__(self):
        super(SocialWebApi, self).__init__()
        self.__usersInfoHelper = UsersInfoHelper()

    @storage_getter('users')
    def usersStorage(self):
        return None

    @w2c(W2CSchema, name='friends_status')
    def friendsStatus(self, cmd):
        storage = self.usersStorage
        friends = storage.getList(MutualFriendsFindCriteria())
        return {
            'action': 'friends_status',
            'friends_status': getStatuses(friends)
        }

    @w2c(_PlayerStatusSchema, name='player_status')
    def isPlayerOnline(self, cmd, ctx):
        callback = ctx.get('callback')
        playerId = cmd.player_id

        def isAvailable():
            player = self.__usersInfoHelper.getContact(playerId)
            return {
                'is_online': player.isOnline() if player is not None else False
            }

        def onNamesReceivedCallback():
            callback(isAvailable())
            self.__usersInfoHelper.onNamesReceived -= onNamesReceivedCallback

        if not bool(self.__usersInfoHelper.getUserName(playerId)):
            self.__usersInfoHelper.onNamesReceived += onNamesReceivedCallback
            self.__usersInfoHelper.syncUsersInfo()
        else:
            return isAvailable()

    @w2c(W2CSchema, name='get_player_info')
    def getPlayerInfo(self, _):
        if not isPlayerAccount():
            return {}
        name = BigWorld.player().name
        clanInfo = g_clanCache.clanInfo
        if clanInfo and len(clanInfo) > 1:
            clanAbbrev = clanInfo[1]
        else:
            clanAbbrev = ''
        return {
            'fullName':
            self.lobbyContext.getPlayerFullName(name, clanInfo=clanInfo),
            'userName':
            name,
            'clanAbbrev':
            clanAbbrev
        }
class SocialWebApi(object):
    def __init__(self):
        super(SocialWebApi, self).__init__()
        self.__usersInfoHelper = UsersInfoHelper()

    @storage_getter('users')
    def usersStorage(self):
        return None

    @w2c(W2CSchema, name='friends_status')
    def friendsStatus(self, cmd):
        storage = self.usersStorage
        friends = storage.getList(MutualFriendsFindCriteria())
        return {
            'action': 'friends_status',
            'friends_status': getStatuses(friends)
        }

    @w2c(_PlayerStatusSchema, name='player_status')
    def isPlayerOnline(self, cmd, ctx):
        callback = ctx.get('callback')
        playerId = cmd.player_id

        def isAvailable():
            player = self.__usersInfoHelper.getContact(playerId)
            return {
                'is_online': player.isOnline() if player is not None else False
            }

        def onNamesReceivedCallback():
            callback(isAvailable())
            self.__usersInfoHelper.onNamesReceived -= onNamesReceivedCallback

        if not bool(self.__usersInfoHelper.getUserName(playerId)):
            self.__usersInfoHelper.onNamesReceived += onNamesReceivedCallback
            self.__usersInfoHelper.syncUsersInfo()
        else:
            return isAvailable()
Exemplo n.º 3
0
class UtilWebApiMixin(object):
    itemsCache = dependency.descriptor(IItemsCache)
    goodiesCache = dependency.descriptor(IGoodiesCache)
    _webCtrl = dependency.descriptor(IWebController)
    _lnkCtrl = dependency.descriptor(IExternalLinksController)

    def __init__(self):
        super(UtilWebApiMixin, self).__init__()
        self.__usersInfoHelper = UsersInfoHelper()

    @w2c(_SetCounterSchema, 'set_counter')
    def setCounterState(self, cmd):
        alias = _COUNTER_IDS_MAP.get(cmd.id)
        if alias is not None:
            g_eventBus.handleEvent(HasCtxEvent(eventType=HEADER_BUTTONS_COUNTERS_CHANGED_EVENT, ctx={'alias': alias,
             'value': cmd.value or ''}))
        return

    @w2c(_GetCountersSchema, 'get_counters')
    def getCountersInfo(self, cmd):
        ids = cmd.id_list or _COUNTER_IDS_MAP.keys()
        counters = AccountSettings.getCounters(NEW_LOBBY_TAB_COUNTER)
        return {id:counters.get(_COUNTER_IDS_MAP[id]) for id in ids if id in _COUNTER_IDS_MAP}

    @w2c(W2CSchema, 'blink_taskbar')
    def blinkTaskbar(self, _):
        showInvitationInWindowsBar()

    @w2c(_RunTriggerChainSchema, 'run_trigger_chain')
    def runTriggerChain(self, cmd):
        chainID = cmd.trigger_chain_id
        runSalesChain(chainID, reloadIfRun=True, isStopForced=True)

    @w2c(_ShowToolTipSchema, 'show_tooltip')
    def showTooltip(self, cmd):
        tooltipType = cmd.tooltipType
        itemId = cmd.itemId
        args = []
        withLongIntArgs = (TC.AWARD_SHELL,)
        withLongOnlyArgs = (TC.AWARD_VEHICLE,
         TC.AWARD_MODULE,
         TC.INVENTORY_BATTLE_BOOSTER,
         TC.BOOSTERS_BOOSTER_INFO,
         TC.BADGE,
         TC.TECH_CUSTOMIZATION_ITEM)
        if tooltipType in withLongIntArgs:
            args = [itemId, 0]
        elif tooltipType in withLongOnlyArgs:
            args = [itemId]
        elif tooltipType == TC.ACHIEVEMENT:
            dossier = self.itemsCache.items.getAccountDossier()
            dossierCompDescr = dumpDossier(self.itemsCache.items.getAccountDossier())
            achievement = dossier.getTotalStats().getAchievement((cmd.blockId, itemId))
            args = [dossier.getDossierType(),
             dossierCompDescr,
             achievement.getBlock(),
             cmd.itemId,
             isRareAchievement(achievement)]
        self.__getTooltipMgr().onCreateTypedTooltip(tooltipType, args, 'INFO')

    @w2c(_ShowItemTooltipSchema, 'show_item_tooltip')
    def showItemTooltip(self, cmd):
        itemType = cmd.type
        if itemType == ItemPackType.CREW_BOOK:
            itemId = makeIntCompactDescrByID('crewBook', CrewBookCacheType.CREW_BOOK, cmd.id)
        else:
            itemId = getCDFromId(itemType=cmd.type, itemId=cmd.id)
        rawItem = ItemPackEntry(type=itemType, id=itemId, count=cmd.count or 1, extra=cmd.extra or {})
        item = lookupItem(rawItem, self.itemsCache, self.goodiesCache)
        showItemTooltip(self.__getTooltipMgr(), rawItem, item)

    @w2c(_ShowAwardsTooltipSchema, 'show_awards_tooltip')
    def showAwardsTooltip(self, cmd):
        showAwardsTooltip(self.__getTooltipMgr(), cmd.type, cmd.data)

    @w2c(_ShowCustomTooltipSchema, 'show_custom_tooltip')
    def showCustomTooltip(self, cmd):
        self.__getTooltipMgr().onCreateComplexTooltip(makeTooltip(header=cmd.header, body=cmd.body), 'INFO')

    @w2c(_ShowSimpleTooltipSchema, 'show_simple_tooltip')
    def showSimpleTooltip(self, cmd):
        self.__getTooltipMgr().onCreateComplexTooltip(makeTooltip(body=cmd.body), 'INFO')

    @w2c(W2CSchema, 'hide_tooltip')
    def hideToolTip(self, _):
        self.__getTooltipMgr().hide()

    @w2c(W2CSchema, 'hide_window_tooltip')
    def hideWulfToolTip(self, _):
        self.__getTooltipMgr().onHideTooltip('')

    @w2c(_ShowAdditionalRewardsTooltipSchema, 'show_additional_rewards_tooltip')
    def showAdditionalRewardsTooltip(self, cmd):
        bonuses = []
        for key, value in cmd.rewards.iteritems():
            bonuses.extend(getNonQuestBonuses(key, value))

        self.__getTooltipMgr().onCreateWulfTooltip(TC.ADDITIONAL_REWARDS, [bonuses], cmd.x, cmd.y)

    @w2c(W2CSchema, 'server_timestamp')
    def getCurrentLocalServerTimestamp(self, _):
        return time_utils.getCurrentLocalServerTimestamp()

    @w2c(_PlatformProductListSchema, name='fetch_product_list')
    def handleFetchProductList(self, cmd):
        ctx = PlatformFetchProductListCtx(cmd)
        response = yield self._webCtrl.sendRequest(ctx=ctx)
        if response.isSuccess():
            yield {'result': response.getData()}
        else:
            yield {'error': self.__getErrorResponse(response.data, 'Unable to fetch product list.')}

    @w2c(_AccountAttribute, name='get_account_attribute_by_prefix')
    def handleGetAccountAttributeByPrefix(self, cmd):
        ctx = SPAAccountAttributeCtx(cmd)
        response = yield self._webCtrl.sendRequest(ctx=ctx)
        if response.isSuccess():
            yield {'result': response.getData()}
        else:
            yield {'error': self.__getErrorResponse(response.data, 'Unable to obtain account attrs.')}

    @storage_getter('users')
    def usersStorage(self):
        return None

    @w2c(_ChatAvailabilitySchema, 'check_if_chat_available')
    def checkIfChatAvailable(self, cmd, ctx):
        callback = ctx.get('callback')
        receiverId = cmd.receiver_id

        def isAvailable():
            receiver = self.__usersInfoHelper.getContact(receiverId)
            return receiver.hasValidName() and not receiver.isIgnored()

        def onNamesReceivedCallback():
            callback(isAvailable())

        if not bool(self.__usersInfoHelper.getUserName(receiverId)):
            self.__usersInfoHelper.onNamesReceived += onNamesReceivedCallback
            self.__usersInfoHelper.syncUsersInfo()
        else:
            return isAvailable()

    @w2c(_VehicleCustomizationPreviewSchema, 'can_install_style')
    def canStyleBeInstalled(self, cmd):
        result = canInstallStyle(cmd.style_id)
        return {'can_install': result.canInstall}

    def __getTooltipMgr(self):
        appLoader = dependency.instance(IAppLoader)
        return appLoader.getApp().getToolTipMgr()

    @staticmethod
    def __getErrorResponse(data, defaultError=''):
        return data if data else {'description': defaultError}

    @w2c(_SelectBattleTypeSchema, 'select_battle_type')
    def selectBattleType(self, cmd):
        battle_selector_items.getItems().select(cmd.battle_type, onlyActive=True)

    @w2c(_UrlInfoSchema, 'get_url_info')
    def getUrlInfo(self, cmd):
        external = self._lnkCtrl.externalAllowed(cmd.url)
        return {'external_allowed': external}