Example #1
0
    def _sendActiveReward(self, userId, rewardKind, scheduleId):
        # 发奖接口
        if ftlog.is_debug():
            ftlog.debug('ActivityWxUserActive._sendActiveReward userId= ',
                        userId, 'rewardKind= ', rewardKind, 'scheduleId= ',
                        scheduleId)
        actInstance = _getActInstance(userId)
        if actInstance:
            userData, expireDay, expireWeek = UserActiveData(userId).loadData()
            if rewardKind == ActiveRewardItem.DAY:
                reward = actInstance.getDayRewardByScheduleId(scheduleId)
                if not reward:
                    raise ActivityWxException(-6, '您没有获得奖励哦~')
                if expireDay:
                    raise ActivityWxException(-7, '您来晚了哦,明天记得早点领取哦~')
                if scheduleId in userData.activeDataDay.scheduleIdList:
                    raise ActivityWxException(-8, '您已领取奖励哦~')
                if userData.activeDataDay.active < reward.active:
                    raise ActivityWxException(-9, '您的日活跃度不够哦~')

                dizhu_util.sendRewardItems(userId, reward.rewards, None,
                                           'ACTIVE_REWARD', 0)
                bireport.reportGameEvent('ACTIVE_REWARDS', userId,
                                         DIZHU_GAMEID, 0, 0, 0, 0, 0, 0,
                                         [scheduleId],
                                         sessiondata.getClientId(userId))
                userData.addDayScheduleId(scheduleId)
                return {
                    'rewards': TYContentItem.encodeList(reward.rewards),
                    'success': 1
                }
            else:
                reward = actInstance.getWeekRewardByScheduleId(scheduleId)
                if not reward:
                    raise ActivityWxException(-6, '您没有获得奖励哦~')

                if expireWeek:
                    raise ActivityWxException(-7, '您来晚了哦,下周记得早点领取哦~')

                if scheduleId in userData.activeDataWeek.scheduleIdList:
                    raise ActivityWxException(-8, '您已领取奖励哦~')
                if userData.activeDataWeek.active < reward.active:
                    raise ActivityWxException(-9, '您的周活跃度不够哦~')

                dizhu_util.sendRewardItems(userId, reward.rewards, None,
                                           'ACTIVE_REWARD', 0)
                userData.addWeekScheduleId(scheduleId)
                bireport.reportGameEvent('ACTIVE_REWARDS', userId,
                                         DIZHU_GAMEID, 0, 0, 0, 0, 0, 0,
                                         [scheduleId],
                                         sessiondata.getClientId(userId))
                return {
                    'rewards': TYContentItem.encodeList(reward.rewards),
                    'success': 1
                }
        raise ActivityWxException(-10, '活动不存在')
Example #2
0
    def _do_room__signin(self, msg):
        if ftlog.is_debug():
            ftlog.debug('DizhuErdayiMatchCtrlRoom._do_room__signin', msg)
        userId = msg.getParam('userId')
        signinParams = msg.getParam('signinParams', {})
        feeIndex = msg.getParam('feeIndex', 0)

        if ftlog.is_debug():
            ftlog.debug('DizhuErdayiMatchCtrlRoom._do_room__signin', 'roomId=',
                        self.roomId, 'userId=', userId, 'signinParams=',
                        signinParams, 'feeIndex=', feeIndex)

        try:
            mp = MsgPack()
            mp.setCmd('m_signin')
            self._ensureCanSignInMatch(userId, mp)
            signer = self.match.signin(userId, feeIndex)
            clientId = signer.clientId if signer else sessiondata.getClientId(
                userId)
            finalUserChip = userchip.getChip(userId)
            bireport.reportGameEvent('MATCH_SIGN_UP', userId, DIZHU_GAMEID,
                                     self.roomId, 0, 0, 0, 0, 0, [], clientId,
                                     0, finalUserChip)
        except MatchException, e:
            self._handleMatchException(e, userId, mp)
Example #3
0
    def _fix_user_task_unit(self, user_task_unit, timestamp):
        from poker.entity.dao import sessiondata
        task_pool = user_task_unit.taskUnit.poolList[0]
        assert isinstance(task_pool, HallTaskKindPoolWithCond)
        clientId = sessiondata.getClientId(user_task_unit.userId)

        # 检查过期条件
        if task_pool.visible_cond and \
                not task_pool.visible_cond.check(self.gameId, user_task_unit.userId, clientId, timestamp):
            return TYUserTaskUnit(user_task_unit.userId,
                                  user_task_unit.taskUnit)
        tasklist = user_task_unit.taskList
        if tasklist:
            for task in tasklist:
                if not task.gotReward:
                    return user_task_unit  # 还有任务没领奖
        else:  # 身上没任务
            # 检查接取条件
            if task_pool.accepted_cond and not task_pool.accepted_cond.check(
                    self.gameId, user_task_unit.userId, clientId, timestamp):
                return user_task_unit

        # 接新任务
        task_kind = task_pool.nextTaskKind(task_order=len(tasklist))
        if task_kind:
            task = task_kind.newTask(None, timestamp)
            user_task_unit.addTask(task)
        return user_task_unit
Example #4
0
    def checkActivityActive(self, userId, timeStamp=None, clientId=None):
        if not self._open:
            return False

        timeStamp = pktimestamp.getCurrentTimestamp(
        ) if not timeStamp else timeStamp
        if self.checkTime(timeStamp) != 0:
            if ftlog.is_debug():
                ftlog.debug('ActivityScoreRanking.checkActivityActive:',
                            'userId=', userId, 'actId=', self.actId,
                            'checkTime=False')
            return False

        if self.isOutOfTime():
            if ftlog.is_debug():
                ftlog.debug('ActivityScoreRanking.checkActivityActive:',
                            'userId=', userId, 'actId=', self.actId,
                            'outOfTime')
            return False

        clientId = clientId or sessiondata.getClientId(userId)
        user_gameId = strutil.getGameIdFromHallClientId(clientId)
        intClientId = pokerconf.clientIdToNumber(clientId)

        if user_gameId not in self._hallGameIds:
            return False

        if intClientId not in self._clientIds:
            if ftlog.is_debug():
                ftlog.debug('ActivityScoreRanking.checkActiveFalse: userId=',
                            userId, 'intClientId=', intClientId, 'clientIds=',
                            self._clientIds)
            return False
        return True
Example #5
0
    def getUrl(self, gameId, userId, url_replace_dict=None):
        if self.def_url:
            return self.def_url

        shareUrl = self.url.getValue(userId, gameId)
        if ftlog.is_debug():
            ftlog.debug('HallShare.getUrl url: ', shareUrl)

        url_replace_dict = url_replace_dict if url_replace_dict else {
            'promoteCode': userId,
            'encryptCode': self.encryptCode(userId)
        }
        url_replace_dict['uid'] = userId

        clientId = sessiondata.getClientId(userId)
        ok, cid, mc, sc = self.parseClientId(clientId)
        if ok:
            url_replace_dict['mc'] = mc
            url_replace_dict['sc'] = sc
            url_replace_dict['cid'] = cid

        if shareUrl.find('${urlPrefix}'):
            url_replace_dict['urlPrefix'] = self.randomUrlPrefix()
        # 替换域名
        return halldomains.replacedDomain(shareUrl, url_replace_dict)
Example #6
0
def _sendUserBehaviourReward(event):
    userId = event.userId
    behaviourConf = dizhuconf.getUserBehaviourReward()
    if not _checkExpectedUser(userId, behaviourConf):
        return
    try:
        ret = daobase.executeUserCmd(event.userId, 'HGET', 'userBehaviour:6:' + str(event.userId), 'info')
        if ret:
            behaviourInfo = strutil.loads(ret)
            behaviourType = behaviourInfo.get('type', 0)
            clientId = sessiondata.getClientId(event.userId)
            if behaviourType == BEHAVIOUR_TYPE_REWARD:
                _changeUserBehaviourInfo(event.userId, behaviourInfo, behaviourConf)
                reportGameEvent('DIZHU_BEHAVIOUR_GROUP', event.userId, DIZHU_GAMEID, 0, 0, 0, 0, behaviourType, 0, [],
                                clientId)
            elif behaviourType == BEHAVIOUR_TYPE_NOUSE:
                behaviourInfo['type'] = BEHAVIOUR_TYPE_NOUSEED
                behaviourInfo['date'] = int(dizhu_util.calcTodayIssueNum())
                daobase.executeUserCmd(userId, 'HSET', 'userBehaviour:6:' + str(userId), 'info',
                                       strutil.dumps(behaviourInfo))
                reportGameEvent('DIZHU_BEHAVIOUR_GROUP', event.userId, DIZHU_GAMEID, 0, 0, 0, 0, behaviourType, 0, [], clientId)
        #else #这个分支在玩家登陆时处理过了,无对应属性的玩家不处理。
        if ftlog.is_debug():
            ftlog.debug('userBehaviour.setUserData userId=', event.userId, 'ret=', ret)
    except Exception, e:
        ftlog.warn('_sendUserBehaviourReward userId=', userId, 'error=', e)
def gainUserRanklistReward(userId, rankId, issueNum, clientId=None):
    # 发放周榜奖励
    userData = loadUserData(userId, rankId, issueNum)
    if not userData:
        raise TYBizException(-1, '没有找到用户数据')

    if userData.rewardState == RewardState.ST_NO_REWARD:
        raise TYBizException(-1, '本期没有奖励可领取')

    if userData.rewardState == RewardState.ST_GAIN_REWARD:
        raise TYBizException(-1, '已经领取了奖励')

    clientId = clientId or sessiondata.getClientId(userId)
    rankRewards = findRankRewardsByRank(rankId, issueNum, clientId,
                                        userData.rank)
    if not rankRewards:
        if ftlog.is_debug():
            ftlog.debug('gainUserRanklistReward rankReward is None. userId=',
                        userId, 'rankId=', rankId, 'issueNum=', issueNum,
                        'clientId=', clientId)
        # TODO warn or error
        raise TYBizException(-1, '未取到对应奖励配置')

    userData.rewardState = RewardState.ST_GAIN_REWARD
    saveUserData(userData)

    contentItems = TYContentItem.decodeList(rankRewards.get('items'))
    assetList = dizhu_util.sendRewardItems(userId, contentItems,
                                           _scoreRankConf.rewardMail,
                                           'DIZHU_SCORE_RANKLIST', int(rankId))

    ftlog.info('gainUserRanklistReward', 'userId=', userId, 'rankId=', rankId,
               'issueNum=', issueNum, 'rank=', userData.rank, 'rewards=',
               [(atp[0].kindId, atp[1]) for atp in assetList])
    return assetList
 def loadStatus(self, userId, timestamp):
     jstr = None
     status = RPTaskStatus(userId)
     try:
         jstr = daobase.executeUserCmd(
             userId, 'hget', 'rptask:%s:%s' % (HALL_GAMEID, userId),
             'status')
         if ftlog.is_debug():
             ftlog.debug('RPTaskSystem.loadStatus', 'gameId=', self.gameId,
                         'userId=', userId, 'jstr=', jstr)
         if jstr:
             d = strutil.loads(jstr)
             self._decodeStatus(status, d)
             # 没有任务或者当前任务不是微信绑定任务则设置为所有任务完成状态
             if not status.finished:
                 clientId = sessiondata.getClientId(status.userId)
                 if not UserConditionNewUser().check(
                         HALL_GAMEID, status.userId, clientId, timestamp):
                     status.finished = 1
         else:
             self._initStatus(status, timestamp)
             self.saveStatus(status)
     except Exception, e:
         ftlog.error('RPTaskSystem.loadStatus', 'gameId=', self.gameId,
                     'userId=', userId, 'jstr=', jstr, 'err=', e.message)
Example #9
0
    def getRewardsList(self, userId, rankRewardsList, mixId):
        '''
        获取渠道奖励列表
        '''
        clientId = sessiondata.getClientId(userId)
        try:
            rankRewardsChannelList = [
                MatchRankRewards().decodeFromDict(r)
                for r in dizhuhallinfo.getArenaMatchSessionRankRewards(
                    userId,
                    int(mixId) if mixId else self._room.bigRoomId, clientId)
            ]
        except:
            rankRewardsChannelList = []

        rankRewardsListCopy = copy.deepcopy(rankRewardsList)
        for index, rankRewards in enumerate(rankRewardsListCopy):
            for rankRewardsChannel in rankRewardsChannelList:
                if rankRewards.startRank == rankRewardsChannel.startRank and rankRewards.endRank == rankRewardsChannel.endRank:
                    rankRewardsListCopy[index] = rankRewardsChannel

        if ftlog.is_debug():
            ftlog.debug('MatchRankRewardsSelectorDizhu.getRewardsList userId=',
                        userId, 'rankRewardsList=', rankRewardsList,
                        'rankRewardsChannelList=', rankRewardsChannelList,
                        'rankRewardsListCopy=', rankRewardsListCopy)

        return rankRewardsListCopy
Example #10
0
def sendShareForWXRedEnvelope(userId, record, item):
    try:
        action = item.itemKind.findActionByName('exchange')
        from hall.entity.hallitem import TYItemActionExchange
        if isinstance(
                action,
                TYItemActionExchange) and action.isWechatRedPack():  # 微信红包
            from poker.util import strutil
            from poker.entity.dao import sessiondata
            clientId = sessiondata.getClientId(userId)
            _, cVer, _ = strutil.parseClientId(clientId)
            if cVer >= 3.90:
                from hall.entity import hallshare
                gameId = strutil.getGameIdFromHallClientId(clientId)
                shareId = hallshare.getShareId('wxRedEnvelope', userId, gameId)
                share = hallshare.findShare(shareId)
                if share:
                    todotask = share.buildTodotask(HALL_GAMEID, userId,
                                                   'wxRedEnvelope')
                    if todotask:
                        from hall.entity.todotask import TodoTaskHelper
                        TodoTaskHelper.sendTodoTask(gameId, userId, todotask)
    except:
        ftlog.error('sendShareForWXRedEnvelope', 'userId=', userId,
                    'exchangeId=', record.exchangeId, 'itemId=', item.itemId,
                    'itemKindId=', item.kindId)
Example #11
0
def _getThirdPartyUserInfo(userId):
    '''
    取得用户的基本账户的信息
    玩家昵称
    玩家id
    钻石数量
    金币数量
    奖券数量
    魅力值
    vip等级
    '''
    userdata.checkUserData(userId)
    ukeys = [
        UserDataSchema.NAME, UserDataSchema.SEX, UserDataSchema.DIAMOND,
        UserDataSchema.CHIP, UserDataSchema.COUPON, UserDataSchema.CHARM,
        UserDataSchema.PURL, UserDataSchema.CREATETIME
    ]
    udataDb = userdata.getAttrs(userId, ukeys)
    udata = dict(zip(ukeys, udataDb))
    # vip信息
    udata['vipInfo'] = hallvip.userVipSystem.getVipInfo(userId)

    # 游戏信息
    clientId = sessiondata.getClientId(userId)
    gameInfo = hallaccount.getGameInfo(userId, clientId)
    udata['gameInfo'] = gameInfo.get('dashifen', {})
    return udata
Example #12
0
    def onUserLogin(cls, event):
        ftlog.debug("SkillLevelGift.onUserLogin: event=", event)

        # gameId = 6
        userId = event.userId
        clientId = sessiondata.getClientId(userId)
        gameId = strutil.getGameIdFromHallClientId(clientId)
        ddzconf = cls.getDdzActivityConf()
        mapkey = "SkillLevelGift" + ddzconf.get("start", "")

        if gameId != DIZHU_GAMEID:
            return

        toggle = ddzconf.get("toggle", False)
        ftlog.debug("SkillLevelGift.onUserLogin: userId=", userId, "open_toggle=", toggle)
        if not toggle:
            return

        isFirst = Redis.isFirst(userId, mapkey)
        ftlog.debug("SkillLevelGift.onUserLogin: userId=", userId, "isFirst=", isFirst)
        if not isFirst:
            return

        # 发放道具
        mail = ddzconf.get("mail", "")
        assets = ddzconf.get("assets")
        UserBag.sendAssetsToUser(gameId, userId, assets, 'DDZ_ATC_SKILLLEVEL_GIFT', mail)
        ftlog.debug("SkillLevelGift.onUserLogin: userId=", userId, "send assets=", assets, "mail=", mail)
Example #13
0
    def get_award(self, uid):
        if not self.checkOperative():
            return 'acitivity expired!'

        actkey = ACTIVITY_KEY.format(HALL_GAMEID, uid, self.getid())
        weekcnt, daycnt = self._get_click_cnt(uid, actkey)
        if weekcnt >= self._clientConf['config'][
                'weeklimit'] or daycnt >= self._clientConf['config'][
                    'daylimit']:
            return 'awardcnt:({},{}) expand limitcnt!'.format(weekcnt, daycnt)

        shareid = self._serverConf["share"]
        share = hallshare.findShare(shareid)
        if not share:
            return 'share:{} not exist!'.format(shareid)

        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_DAY_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_WEEK_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_TOTAL_CNT, 1)
        hallshare.sendReward(HALL_GAMEID, uid, share, 'share_click')
        # 分享BI日志汇报
        clientid = sessiondata.getClientId(uid)
        bireport.reportGameEvent('SHARE_CALLBACK', uid, HALL_GAMEID, shareid,
                                 0, 0, 0, 0, 0, [], clientid)
        if share.mail:
            message.send(HALL_GAMEID, message.MESSAGE_TYPE_SYSTEM, uid,
                         share.mail)
        return 'ok'
Example #14
0
    def _handleSigninFeeNotEnoughException_V3_772(cls, room, ex, uid, mo):
        payOrder = ex.fee.getParam('payOrder')
        clientId = sessiondata.getClientId(uid)
        ftlog.debug("groupmatch._handleSigninFeeNotEnoughException_V3_772", "userId", uid, "fee.itemId=", ex.fee.assetKindId, "fee.params=", ex.fee.params)
        ftlog.debug("groupmatch._handleSigninFeeNotEnoughException_V3_772, userId=", uid, "payOrder=", payOrder)

        if payOrder:
            product, _shelves = hallstore.findProductByPayOrder(room.gameId, uid, clientId, payOrder)
            if not product:
                cls.sendDizhuFailureMsg(room.gameId, uid, '报名失败', ex.fee.failure, None)
                return

            buyType = ''
            btnTxt = ''
            if ex.fee.assetKindId == hallitem.ASSET_CHIP_KIND_ID: # 金币是报名费
                orderShow = TodoTaskOrderShow.makeByProduct(ex.fee.failure, '', product, buyType)
                orderShow.setParam('sub_action_btn_text', btnTxt)
                mo = TodoTaskHelper.makeTodoTaskMsg(room.gameId, uid, orderShow)
                router.sendToUser(mo, uid)
                return

        ## 其他报名费/gotoshop
        todotask = ex.fee.getParam('todotask')
        todotask_str = None
        button_title = None
        ftlog.debug("groupmatch._handleSigninFeeNotEnoughException_V3_772, userId=", uid, "todotask=", todotask)
        if todotask:
            button_title = "去商城"
            todotask_str = hallpopwnd.decodeTodotaskFactoryByDict(todotask).newTodoTask(room.gameId, uid, clientId).toDict()
        cls.sendDizhuFailureMsg(room.gameId, uid, '报名失败', ex.fee.failure, todotask_str, button_title)
Example #15
0
def doSendLedToUser(userId):
    gameIdList = onlinedata.getGameEnterIds(userId)
    if not gameIdList:
        return

    clientId = sessiondata.getClientId(userId)
    _, clientVer, _ = strutil.parseClientId(clientId)
    for gameId in gameIdList:
        try:
            leds = getLedMsgList(gameId)
            if ftlog.is_debug():
                ftlog.debug('hallled.doSendLedToUser gameId=', gameId,
                            'gameId=', gameId, 'userId=', userId, 'clientId=',
                            clientId, 'leds=', leds)
            if leds:
                msgDict = leds[0][2]
                if clientVer >= 3.6:
                    mo = MsgPack()
                    mo.setCmd('led')
                    for k, v in msgDict.iteritems():
                        mo.setResult(k, v)
                else:
                    mo = MsgPack()
                    mo.setCmd('led')
                    if gameId in (1, 8):
                        msgDictV2 = translateToMsgDictV2(msgDict)
                        if msgDictV2:
                            mo.setKey('richText', msgDictV2.get('richText'))
                    msgV1 = translateToMsgDictV1(msgDict)
                    if msgV1:
                        gameId = msgDict.get('gameId', leds[0][1])
                        mo.setKey('result', [[leds[0][0], gameId, msgV1]])
                router.sendToUser(mo, userId)
        except:
            ftlog.error()
Example #16
0
def _fix_user_task_unit(self, user_task_unit, timestamp):
    from poker.entity.dao import sessiondata
    clientId = sessiondata.getClientId(user_task_unit.userId)
    
    # 所有任务池的检查过期条件是一样的
    task_pool_0 = user_task_unit.taskUnit.poolList[0]
    if task_pool_0.visible_cond and \
            not task_pool_0.visible_cond.check(self.gameId, user_task_unit.userId, clientId, timestamp):
        ftlog.debug('task pool not match visible cond, return...')
        return TYUserTaskUnit(user_task_unit.userId, user_task_unit.taskUnit)
    
    tasklist = user_task_unit.taskList
    if tasklist:
        for task in tasklist:
            if not task.gotReward:
                return user_task_unit  # 还有任务没领奖

    
    for task_pool in user_task_unit.taskUnit.poolList:
        assert isinstance(task_pool, HallTaskKindPoolWithCond)
        # 检查接取条件
        if task_pool.accepted_cond and not task_pool.accepted_cond.check(self.gameId, user_task_unit.userId, clientId, timestamp):
            ftlog.debug('can not accept this task pool, continue...')
            continue

        # 接新任务
        task_kind = task_pool.nextTaskKind(task_order=len(tasklist))
        if task_kind:
            task = task_kind.newTask(None, timestamp)
            user_task_unit.addTask(task)
            ftlog.debug('find task pool, break...')
            break
        
    return user_task_unit
Example #17
0
 def getUserShareControlInfo(cls, userId):
     burialIdList = []
     clientId = sessiondata.getClientId(userId)
     for burialIdConf in _wxShareControlConf.burialIdList:
         sType = None
         for shareOrVideoConf in burialIdConf.shareOrVideo:
             if shareOrVideoConf.condition.check(DIZHU_GAMEID, userId, clientId, pktimestamp.getCurrentTimestamp()):
                 sType = shareOrVideoConf.type
                 break
         burialIdList.append({
             'burialId': burialIdConf.burialId,
             'shareOrVideo': sType
         })
     if ftlog.is_debug():
         ftlog.debug('WxShareControlHelper.getUserShareControlInfo userId=', userId,
                     'winStreakRewardSwitch=', _wxShareControlConf.winStreakRewardSwitch,
                     'matchRewardSwitch', _wxShareControlConf.matchRewardSwitch,
                     'shareFakeSwitch', _wxShareControlConf.shareFakeSwitch,
                     'burialIdList', burialIdList)
     return {
         'winStreakRewardSwitch': _wxShareControlConf.winStreakRewardSwitch,
         'matchRewardSwitch': _wxShareControlConf.matchRewardSwitch,
         'shareFakeSwitch': _wxShareControlConf.shareFakeSwitch,
         'burialIdList': burialIdList
     }
Example #18
0
 def report_bi_game_event(self,
                          eventId,
                          userId,
                          roomId,
                          tableId,
                          roundId,
                          detalChip,
                          state1,
                          state2,
                          cardlist,
                          tag=''):
     try:
         finalUserChip = userchip.getChip(userId)
         finalTableChip = 0
         clientId = sessiondata.getClientId(userId)
         bireport.reportGameEvent(eventId, userId, 6, roomId, tableId,
                                  roundId, detalChip, state1, state2,
                                  cardlist, clientId, finalTableChip,
                                  finalUserChip)
         self._logger.debug('PlayerNotifierDizhu.report_bi_game_event tag=',
                            tag, 'eventId=', eventId, 'userId=', userId,
                            'gameId=', 6, 'roomId=', roomId, 'tableId=',
                            tableId, 'roundId=', roundId)
     except:
         self._logger.error(
             'PlayerNotifierDizhu.report_bi_game_event error tag=', tag,
             'eventId=', eventId, 'userId=', userId, 'gameId=', 6,
             'roomId=', roomId, 'tableId=', tableId, 'roundId=', roundId)
Example #19
0
def _getThirdPartyUserInfo(userId):
    '''
    取得用户的基本账户的信息
    玩家昵称
    玩家id
    钻石数量
    金币数量
    奖券数量
    魅力值
    vip等级
    '''
    userdata.checkUserData(userId)
    ukeys = [UserDataSchema.NAME, UserDataSchema.SEX, UserDataSchema.DIAMOND,
             UserDataSchema.CHIP, UserDataSchema.COUPON, UserDataSchema.CHARM,
             UserDataSchema.PURL, UserDataSchema.CREATETIME]
    udataDb = userdata.getAttrs(userId, ukeys)
    udata = dict(zip(ukeys, udataDb))
    # vip信息
    udata['vipInfo'] = hallvip.userVipSystem.getVipInfo(userId)

    # 游戏信息
    clientId = sessiondata.getClientId(userId)
    gameInfo = hallaccount.getGameInfo(userId, clientId)
    udata['gameInfo'] = gameInfo.get('dashifen', {})
    return udata
Example #20
0
 def onWinlose(cls, event):
     clientId = sessiondata.getClientId(event.userId)
     timestamp = pktimestamp.getCurrentTimestamp()
     if ftlog.is_debug():
         ftlog.debug('FiveStarRate.onWinlose userId=', event.userId,
                     'clientId=', clientId,
                     'roomId=', event.roomId,
                     'tableId=', event.tableId,
                     'winlose=', event.winlose.__dict__)
     if not event.winlose.isWin:
         return
     
     winDesc = dizhuconf.getPublicConf('five_star_win_desc', '')
     # 玩家在高倍场馆单局倍数超过128倍并获胜,且获胜得到的金币大于20W时
     if event.winlose.windoubles >= 128:
         hallfivestarrate.triggleFiveStarRateIfNeed(event.userId, clientId, timestamp, winDesc)
         return
     
     # 账号注册时间大于五天、游戏局数超过20局的玩家,连续获胜3局时
     if cls.calcRegisterDays(event.userId, timestamp) > 5:
         winrate, winstreak = gamedata.getGameAttrs(event.userId, DIZHU_GAMEID, ['winrate', 'winstreak'])
         winrate = strutil.loads(winrate, ignoreException=True, execptionValue={'pt':0, 'wt':0})
         try:
             winstreak = 0 if winstreak is None else int(winstreak)
         except:
             winstreak = 0
         if winrate.get('pt', 0) > 20 and winstreak == 3:
             hallfivestarrate.triggleFiveStarRateIfNeed(event.userId, clientId, timestamp, winDesc)
Example #21
0
def resumeItemFromTable(userId, gameId, itemId, count, roomId, tableId):
    """退还房卡,加锁操作"""
    ftlog.debug('user_remote resumeItemFromTable userId:', userId
                , ' gameId:', gameId
                , ' itemId:', itemId
                , ' count:', count
                , ' roomId:', roomId
                , ' tableId:', tableId
                )

    clientId = sessiondata.getClientId(userId)
    loc = onlinedata.checkUserLoc(userId, clientId, gameId)
    ftlog.debug('user_remote resumeItemFromTable loc:', loc)

    lgameId, lroomId, ltableId, lseatId = loc.split('.')
    lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
    if (lroomId != roomId) or (ltableId != tableId):
        ftlog.info('user_remote resumeItemFromTable loc not match, do not resume item. userId:', userId
                   , ' gameId:', gameId
                   , ' itemId:', itemId
                   , ' count:', count
                   , ' roomId:', roomId
                   , ' tableId:', tableId
                   , ' loc:', loc)
        return

    MajiangItem.addUserItemByKindId(userId
                                    , gameId
                                    , itemId
                                    , count
                                    , 'MAJIANG_FANGKA_RETURN_BACK'
                                    , roomId)
Example #22
0
 def report_bi_game_event(self,
                          eventId,
                          userId,
                          roomId,
                          tableId,
                          roundId,
                          detalChip,
                          state1,
                          state2,
                          cardlist,
                          tag=''):
     try:
         clientId = sessiondata.getClientId(userId)
         bireport.reportGameEvent(eventId, userId, 6, roomId, tableId,
                                  roundId, detalChip, state1, state2,
                                  cardlist, clientId, 0, 0)
         ftlog.debug('report_bi_game_event tag=',
                     tag,
                     'eventId=',
                     eventId,
                     'userId=',
                     userId,
                     'gameId=6',
                     'roomId=',
                     roomId,
                     'tableId=',
                     tableId,
                     'roundId=',
                     roundId,
                     caller=self)
     except:
         ftlog.error('report_bi_game_event error tag=', tag, 'eventId=',
                     eventId, 'userId=', userId, 'gameId=6', 'roomId=',
                     roomId, 'tableId=', tableId, 'roundId=', roundId)
Example #23
0
def checkMatchSigninCond(userId, roomId):
    if userId <= 10000:
        # 机器人不检查
        return True, None

    matchCondConf = configure.getGameJson(DIZHU_GAMEID, 'bigmatch.filter', {})
    if not matchCondConf:
        if ftlog.is_debug():
            ftlog.debug(
                'dizhumatchcond.checkMatchSigninCond EmptyMatchCondConf roomId=',
                roomId, 'gameId=', DIZHU_GAMEID, 'userId=', userId,
                'matchCondConf=', matchCondConf)
        return True, None

    bigRoomId = gdata.getBigRoomId(roomId)
    condConf = matchCondConf.get(str(bigRoomId))

    if ftlog.is_debug():
        ftlog.debug('dizhumatchcond.checkMatchSigninCond roomId=', roomId,
                    'gameId=', DIZHU_GAMEID, 'userId=', userId, 'bigRoomId=',
                    bigRoomId, 'condConf=', condConf, 'matchCondConf=',
                    matchCondConf)

    if condConf:
        clientId = sessiondata.getClientId(userId)
        timestamp = pktimestamp.getCurrentTimestamp()
        cond = MatchCondition().decodeFromDict(condConf)
        if not cond.check(DIZHU_GAMEID, userId, clientId, timestamp):
            return False, cond
    return True, None
Example #24
0
    def _handleSigninFeeNotEnoughException(cls, room, ex, uid, mo):
        payOrder = ex.fee.getParam('payOrder')

        clientId = sessiondata.getClientId(uid)
        clientOs, _clientVer, _ = strutil.parseClientId(clientId)
        msg = runcmd.getMsgPack()
        ddzver = msg.getParam('ddzver', 0) if msg else 0

        ftlog.debug("groupmatch._handleSigninFeeNotEnoughException", "userId", uid, "_clientVer=", _clientVer)
        if ddzver >= 3.772:
            cls._handleSigninFeeNotEnoughException_V3_772(room, ex, uid, mo)
            return

        if payOrder:
            clientOs = clientOs.lower()
            product, _shelves = hallstore.findProductByPayOrder(room.gameId, uid, clientId, payOrder)
            if product:
                buyType = ''
                btnTxt = ''
                if ex.fee.assetKindId == hallitem.ASSET_CHIP_KIND_ID and clientOs == 'winpc':
                    user_diamond = userdata.getAttrInt(uid, 'diamond')
                    if user_diamond >= int(product.priceDiamond):
                        buyType = 'consume'
                        btnTxt = '兑换'
                    else:
                        buyType = 'charge'
                        btnTxt = '去充值'
                orderShow = TodoTaskOrderShow.makeByProduct(ex.fee.failure, '', product, buyType)
                orderShow.setParam('sub_action_btn_text', btnTxt)
                mo = TodoTaskHelper.makeTodoTaskMsg(room.gameId, uid, orderShow)
                router.sendToUser(mo, uid)
                return True
        mo = TodoTaskHelper.makeTodoTaskMsg(room.gameId, uid, TodoTaskShowInfo(ex.fee.failure))
        router.sendToUser(mo, uid)
Example #25
0
    def _checkRoomConditions(cls, userId, roomConfig):
        enterRoomCondList = roomConfig.get('enterRoomCond')
        clientId = sessiondata.getClientId(userId)
        if enterRoomCondList:
            try:
                for enterCond in enterRoomCondList:
                    cond = enterCond['cond']
                    msg = enterCond['msg']

                    result = UserConditionRegister.decodeFromDict(cond).check(DIZHU_GAMEID, userId, clientId, pktimestamp.getCurrentTimestamp())
                    if not result:
                        if ftlog.is_debug():
                            ftlog.debug('DizhuQuickStartWx._validEnterRoomConditions',
                                        'gameId=', DIZHU_GAMEID,
                                        'userId=', userId,
                                        'clientId=', clientId,
                                        'roomConfig=', roomConfig,
                                        'enterRoomCond=', enterRoomCondList,
                                        'ret=', msg)
                        return result, msg
                return True, 'ok'
            except Exception, e:
                ftlog.error('DizhuQuickStartWx._validEnterRoomConditions',
                            'gameId=', DIZHU_GAMEID,
                            'userId=', userId,
                            'clientId=', clientId,
                            'roomConfig=', roomConfig,
                            'enterRoomCond=', enterRoomCondList,
                            'err=', e.message)
                return False, e.message
Example #26
0
    def handleBetMsg(self, msg):
        try:
            timestamp = pktimestamp.getCurrentTimestamp()
            nowDT = datetime.fromtimestamp(timestamp)
            # 参数检查
            form = BetForm().fromMsg(msg).checkValid()
            # 检查时间
            if self.startTime and nowDT < self.startTime:
                raise TYBizException(-1, '活动还未开始')

            if self.endTime and nowDT >= self.endTime:
                raise TYBizException(-1, '活动已经结束')

            if self.stopBetTime and nowDT >= self.stopBetTime:
                raise TYBizException(-1, self._serverConf['stopBetDesc'])

            form.clientId = form.clientId or sessiondata.getClientId(
                form.userId)
            bet = self._serverConf[self.BET_KEYS[form.bet]]
            chip, status = self.bet(form.gameId, form.userId, form.clientId,
                                    form.target, bet['amount'], timestamp)
            return self.buildBetResponse(form.gameId, status, chip,
                                         form.target)
        except TYBizException, e:
            return {'ec': e.errorCode, 'info': e.message}
Example #27
0
 def _genInitTaskKindList(self, status, timestamp):
     clientId = sessiondata.getClientId(status.userId)
     for cond, taskKindList in self._initPools:
         if not cond or cond.check(self.gameId, status.userId, clientId,
                                   timestamp):
             return taskKindList
     return self._genRefreshTaskKindList(status, timestamp)
Example #28
0
    def recommendProductIfCan(self, gameId, userId):
        # 没有配置推荐商品,则不推荐
        payOrder = Tool.dictGet(self._clientConf, 'config.server.payOrder')
        if not payOrder:
            return False

        clientId = sessiondata.getClientId(userId)
        product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId,
                                                     payOrder)
        ftlog.debug('FunAct.recommendProductIfCan:', 'userId=', userId,
                    'product=', product)
        # 没有在货架中找到商品
        if not product:
            return False

        translateMap = {
            'product.displayName': product.displayName,
            'product.price': product.price,
            'count': payOrder.get('contains', {}).get('count', 0)
        }
        desc = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipDesc')
        note = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipNote')
        desc = strutil.replaceParams(desc, translateMap)
        note = strutil.replaceParams(note, translateMap)
        todotask = TodoTaskLessBuyOrder(desc, None, note, product)
        TodoTaskHelper.sendTodoTask(gameId, userId, todotask)
        return True
Example #29
0
    def _getQuickStartRoomList(cls, userId, playMode):
        ''' 获取快开房间列表 '''
        clientId = sessiondata.getClientId(userId)
        sessions = hallconf.getHallSessionInfo(DIZHU_GAMEID, clientId)
        sessionRoomInfoList = []
        for session in sessions:
            if session.get('playMode') == playMode:
                for room in session.get('rooms', []):
                    bigRoomId = room.get('id')
                    segment = room.get('segment')
                    ctrlRoomId = bigRoomId * 10000 + 1000
                    mixId = room.get('mixId')
                    roomConfig = cls._getRoomConfigure(ctrlRoomId, mixId)
                    sessionRoomInfoList.append({
                        'bigRoomId': bigRoomId,
                        'ctrlRoomId': ctrlRoomId,
                        'mixId': mixId,
                        'roomConfig': roomConfig,
                        'segment': segment})
                break

        # 房间过滤排序
        if playMode == 'match':
            sessionRoomInfoList.sort(key=lambda x: x['roomConfig'].get('minQuickStartDiamond'))
        else:
            sessionRoomInfoList.sort(key=lambda x: x['roomConfig'].get('minQuickStartChip'))

        if ftlog.is_debug():
            ftlog.debug('DizhuQuickStartWx._getQuickStartRoomList',
                        'userId=', userId,
                        'playMode=', playMode,
                        'sessionRoomInfoList=', sessionRoomInfoList)
        return sessionRoomInfoList
Example #30
0
    def _do_room__signin(self, msg):
        userId = msg.getParam('userId')
        signinParams = msg.getParam('signinParams', {})
        feeIndex = msg.getParam('feeIndex', 0)
        
        if ftlog.is_debug():
            ftlog.debug('DizhuCtrlRoomGroupMatch._do_room__signin',
                       'roomId=', self.roomId,
                       'userId=', userId,
                       'signinParams=', signinParams,
                       'feeIndex=', feeIndex)

        mp = MsgPack()
        mp.setCmd('m_signin')
        try:
            # 检查禁赛
            res, remains = BanHelper.checkBanValid(userId, self.bigRoomId)
            if res:
                raise MatchBanException(remains)

            self.ensureCanSignInMatch(userId, mp)
            signer = self.match.signin(userId, signinParams, feeIndex)
            clientId = signer.clientId if signer else sessiondata.getClientId(userId)
            finalUserChip = userchip.getChip(userId)
            try:
                sequence = int(self.match.curInst.instId.split('.')[1])
            except:
                sequence = 0
            bireport.reportGameEvent('MATCH_SIGN_UP', userId, DIZHU_GAMEID, self.roomId, 0, sequence, 0,
                                     0, 0, [], clientId, 0, finalUserChip)
        except (MatchException, MatchBanException), e:
            self._handleMatchException(e, userId, mp)
    def _doGetNotReceiveReward(cls, userId, clientId=None):
        mo = MsgPack()
        mo.setCmd('dizhu')
        mo.setResult('action', 'score_reward_tip')

        curIssueNum = dizhu_score_ranking.calcIssueNum()
        mo.setResult('curIssn', curIssueNum)

        rankingConf = dizhu_score_ranking.getConf()
        for rankId, rankingDefine in rankingConf.rankingDefineMap.iteritems():
            if not rankingDefine:
                raise TYBizException(-1, '未知的排行榜')

            rankingInfo = dizhu_score_ranking.loadRankingInfo(rankId)
            hisotryItems = cls.pickHistoryItems(rankingInfo, curIssueNum)
            from poker.entity.dao import sessiondata
            clientId = clientId or sessiondata.getClientId(userId)
            notReceive = cls.buildNotReceived(rankingDefine.rankId,
                                              hisotryItems, userId, clientId)
            if notReceive:
                mo.setResult('rankId', rankId)
                mo.setResult('notReceive', notReceive)
                break

        return mo
Example #32
0
 def makeVipInfoResponse(cls,
                         gameId,
                         userVip,
                         vipGiftStates,
                         clientId=None):
     expDesc = cls.buildExpDesc(userVip)
     clientId = clientId or sessiondata.getClientId(userVip.userId)
     mo = MsgPack()
     mo.setCmd('newvip')
     mo.setResult('action', 'vipInfo')
     mo.setResult('gameId', gameId)
     mo.setResult('userId', userVip.userId)
     mo.setResult('vipLevel', userVip.vipLevel.level)
     mo.setResult('vipExpDesc', expDesc)
     mo.setResult('tasks',
                  cls.buildUpLevelTodoTasks(gameId, userVip, clientId))
     if len(vipGiftStates) > 0 and vipGiftStates[0].vipLevel.level == 0:
         del vipGiftStates[0]
     if userVip.vipLevel.nextVipLevel:
         vipGiftStates.append(
             TYVipGiftState(userVip.vipLevel.nextVipLevel,
                            TYVipGiftState.STATE_UNGOT))
         if userVip.vipLevel.level == 0 and userVip.vipLevel.nextVipLevel.nextVipLevel:
             vipGiftStates.append(
                 TYVipGiftState(userVip.vipLevel.nextVipLevel.nextVipLevel,
                                TYVipGiftState.STATE_UNGOT))
     vipInfoList = []
     for vipGiftState in vipGiftStates:
         vipInfoList.append(
             cls.buildVipLevelStateInfo(userVip, vipGiftState))
     mo.setResult('vipInfoList', vipInfoList)
     return mo
Example #33
0
 def doBuyProduct(self, gameId, userId, prodId):
     try:
         clientId = sessiondata.getClientId(userId)
         orderId = self._makeOrderId(gameId, userId, prodId)
         orderDeliveryResult = hallstore.exchangeProduct(gameId, userId, clientId, orderId, prodId, 1)
         mo = StoreHelper.makeProductDeliveryResponse(userId, orderDeliveryResult)
         router.sendToUser(mo, userId)
     except TYBizException, e:
         TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(e.message))
Example #34
0
    def isSuitable(self, userId, gameId):
        if len(self.conditions) == 0:
            return True

        clientId = sessiondata.getClientId(userId)
        for cond in self.conditions:
            if not cond.check(gameId, userId, clientId, pktimestamp.getCurrentTimestamp()):
                return False

        return True
Example #35
0
    def queryFangKaCount(self, gameId, userId, clientId):
        if not clientId:
            clientId = sessiondata.getClientId(userId)
        itemId = hall_fangka.queryFangKaItem(gameId, userId, clientId)

        userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
        item = userBag.getItemByKindId(itemId)
        if not item:
            return 0

        timestamp = pktimestamp.getCurrentTimestamp()
        return item.balance(timestamp)
Example #36
0
 def _doTableManage(self, msg, action):
     '''
     处理来自GR的table_manage命令
     '''
     if action == 'leave':
         userId = msg.getParam("userId")
         assert isinstance(userId, int) and userId > 0
         clientId = sessiondata.getClientId(userId)
         return self._doLeave(msg, userId, clientId)
     elif action == 'clear_table':
         return self._doClearPlayers()
     if action == 'clear_players':
         return self._doClearPlayers()
Example #37
0
 def reportBiGameEvent(self, eventId, userId, roomId, tableId, roundId, detalChip, state1, state2, cardlist, tag=''):
     try:
         finalUserChip = userchip.getChip(userId)
         finalTableChip = 0
         clientId = sessiondata.getClientId(userId)
         bireport.reportGameEvent(eventId, userId, self.gameId, roomId, tableId, roundId, detalChip,
                                  state1, state2, cardlist, clientId, finalTableChip, finalUserChip)
         if ftlog.is_debug():
             ftlog.debug('tag=', tag, 'eventId=', eventId, 'userId=', userId, 'gameId=', self.gameId,
                         'roomId=', roomId, 'tableId=', tableId, 'roundId=', roundId, 'detalChip=', detalChip,
                         caller=self)
     except:
         ftlog.error(getMethodName(), 'tag=', tag, 'eventId=', eventId, 'userId=', userId, 'gameId=', self.gameId)
Example #38
0
    def consumeRooCardsFirstWay(self, table, needRoomCardN):
        gameId = table.gameId

        oneRoomCardGameRoundN = difangConf.getCustomRoomConf(gameId, "oneRoomCardGameRoundN")
        if not oneRoomCardGameRoundN:
            return

        if table.gamePlay.gameSeq % oneRoomCardGameRoundN != 1:
            return

        userId = table.firstPlayerId
        clientId = sessiondata.getClientId(userId)
        self.consumeRoomCard(gameId, userId, 1, clientId)
        table.consumedRoomCardN += 1
Example #39
0
 def _check_param_clientId(self, msg, key, params):
     clientId = msg.getKey(key)
     if clientId and isinstance(clientId, (str, unicode)):
         return None, clientId
     clientId = msg.getParam(key)
     if clientId and isinstance(clientId, (str, unicode)):
         return None, clientId
     ftlog.debug('ERROR !! the msg clientId is not found use session clientId !', msg)
     userId = msg.getParam('userId')
     if userId:
         clientId = sessiondata.getClientId(userId)
         if clientId and isinstance(clientId, (str, unicode)):
             return None, clientId
     return 'ERROR of clientId !' + str(clientId), None
Example #40
0
    def isProductShow(cls, product, userId):
        ftlog.debug('StoreHelper.isProductShow product=', product,
                    'userId=', userId)

        if product.showConditions:
            ftlog.debug('StoreHelper.isProductShow product conditions:', product.showConditions)
            conditions = UserConditionRegister.decodeList(product.showConditions)

            for cond in conditions:
                clientId = sessiondata.getClientId(userId)
                if not cond.check(HALL_GAMEID, userId, clientId, pktimestamp.getCurrentTimestamp()):
                    ftlog.debug('StoreHelper.isProductShow not suitable for condition:', cond)
                    return False
        return True
Example #41
0
    def doBuyProductOld(self, gameId, userId, prodId):
        mo = MsgPack()
        mo.setCmd('buy_prod')
        mo.setResult('gameId', gameId)
        mo.setResult('userId', userId)
        mo.setResult('prodId', prodId)

        try:
            clientId = sessiondata.getClientId(userId)
            orderId = self._makeOrderId(gameId, userId, prodId)
            hallstore.storeSystem.buyProduct(gameId, userId, clientId, orderId, prodId, 1)
            mo.setResult('orderId', orderId)
            router.sendToUser(mo, userId)
        except TYBizException, e:
            mo.setError(e.errorCode, e.message)
Example #42
0
 def checkCompensateOrderId(cls, gameId, userId, orderId, productId):
     '''
     自动补单处理
     '''
     if orderId in ('ios_compensate', 'momo_compensate'):
         ftlog.info('checkCompensateOrderId compensate fix->', gameId, userId, orderId, productId)
         try:
             clientId = sessiondata.getClientId(userId)
             orderId = cls._makeOrderId(gameId, userId, productId)
             order = hallstore.storeSystem.buyProduct(gameId, userId, clientId, orderId, productId, 1)
             orderId = order.orderId
             ftlog.info('checkCompensateOrderId compensate fix->orderId=', orderId)
         except:
             ftlog.error('ERROR checkCompensateOrderId compensate fix !!', gameId, userId, orderId, productId)
     return orderId
Example #43
0
    def onTableGameStart(self, gameId, msg):
        if ftlog.is_debug():
            ftlog.debug("<< |msg", msg, caller=self)

        table = msg.getParam("table")

        bireport.tableStart(table.gameId, table.roomId, table.tableId,
                            table.gamePlay.gameSeq, DiFangPlayersHelper.getPlayingPlayersIds(table))

        for player in DiFangPlayersHelper.getPlayingPlayers(table):
            bireport.reportGameEvent('TABLE_START',
                                     player.userId, gameId, table.roomId, table.tableId,
                                     table.gamePlay.gameSeq,
                                     0, 0, 0, [],
                                     sessiondata.getClientId(player.userId),
                                     player.tableChips)
Example #44
0
    def dict_change_fortune(cls, userid, gameId, roomid, cache = False):
        """ 根据商品信息生成payOrder的字典
        action: pop_fortune&cache_fortune
        Args:
            userid: 玩家userid
            roomid: 房间id
            cache: action命名是否是缓存形式
        """
        clientid = sessiondata.getClientId(userid)
        from hall.entity import hallproductselector, hallitem
        product, _ = hallproductselector.selectZhuanyunProduct(gameId, userid, clientid, roomid)
        if not product:
            return None

        payorder = cls.dict_pay_order(userid, product)

        chip = product.getMinFixedAssetCount(hallitem.ASSET_CHIP_KIND_ID)
        content1 = u'运气不好,来个转运礼包!'
        content2 = u'全国只有1%的人有机会呦!'
        rmblabel = u'¥'+str(product.price)
        chiplabel = chip

        action = "pop_fortune" if True != cache else "cache_fortune"
        return {
            'action': action,
            'params': {
                'content1': content1,
                'content2': content2,
                'rmb': rmblabel,
                'coin': chiplabel,
                'buttons': [
                        {
                            'content': u"立即购买",
                            'tasks': [
                                payorder
                            ]

                        },
                        {
                            'content': u'取消',
                            'tasks': [

                            ]
                        }
                    ]
                }
        }
Example #45
0
 def _check_param_clientId(self, key, params):
     clientId = runhttp.getParamStr(key, '')
     ftlog.debug('BaseHttpMsgChecker._check_param_clientId key=', key,
                 'params=', params,
                 'clientId=', clientId)
     if clientId and isinstance(clientId, (str, unicode)):
         return None, clientId
     userId = runhttp.getParamInt('userId', 0)
     ftlog.debug('BaseHttpMsgChecker._check_param_clientId key=', key,
                 'params=', params,
                 'clientId=', clientId,
                 'userId=', userId)
     if userId:
         clientId = sessiondata.getClientId(userId)
         if clientId and isinstance(clientId, (str, unicode)):
             return None, clientId
     return 'ERROR of clientId !' + str(clientId), None
Example #46
0
    def _conform(self, gameId, userAssets, item, timestamp, params):
        userId = userAssets.userId
        clientId = sessiondata.getClientId(userId)
        from hall.entity import hallaccount
        info = hallaccount.getGameInfo(userId, clientId)

        if ftlog.is_debug():
            ftlog.debug('ItemActionConditionGameDashifenLevel.check gameInfo:', info)

        dashifen = info.get('dashifen', {})

        level = 0
        if gameId in dashifen:
            level = dashifen[gameId].get('level', 0)
            if ftlog.is_debug():
                ftlog.debug('ItemActionConditionGameDashifenLevel.check level:', info)
        else:
            return False

        return (self.minLevel == -1 or level >= self.minLevel) \
               and (self.maxLevel == -1 or level < self.maxLevel)
Example #47
0
    def callLaterFunc(self, interval, func, userId=0, timer=None, msgPackParams=None):
        '''延时调用table对象的一个函数
           原理:延时调用table.doTableCall命令,通过此命令调用table对象的一个函数
           意义:table.doTableCall函数会锁定table对象,保证数据操作的同步性
        '''

        if msgPackParams == None:
            msgPackParams = {}
        msgPackParams["userId"] = userId
        clientId = sessiondata.getClientId(userId) if userId > 0 else None
        msgPackParams["clientId"] = clientId
        msgPackParams["func"] = func
        action = "CL_FUNC"

        if timer == None:
            timer = TYTableTimer(self)
        timer.setup(interval, action, msgPackParams, cancelLastTimer=False)

        funcName = func.func.func_name
        if ftlog.is_debug():
            ftlog.debug(">> |clientId, userId, tableId:", clientId, userId, self.tableId,
                        "|action, func, interval:", action, funcName, interval, caller=self)
Example #48
0
    def consumeRoomCard(self, gameId, userId, needRoomCardN, clientId):
        """消耗房卡"""
        ftlog.info("consumeRoomCard << |userId, needRoomCardN, clientId", userId, needRoomCardN, clientId, caller=self)
        if not needRoomCardN:
            return

        if not clientId:
            clientId = sessiondata.getClientId(userId)
        itemId = hall_fangka.queryFangKaItem(gameId, userId, clientId)

        userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
        item = userBag.getItemByKindId(itemId)
        if not item:
            return

        timestamp = pktimestamp.getCurrentTimestamp()
        count = userBag.consumeItemUnits(gameId, item, needRoomCardN, timestamp, 'ITEM_USE', item.kindId)

        changed = ['item']
        if isinstance(item, TYDecroationItem):
            changed.append('decoration')
        datachangenotify.sendDataChangeNotify(gameId, userId, changed)
Example #49
0
    def handleBetMsg(self, msg):
        try:
            timestamp = pktimestamp.getCurrentTimestamp()
            nowDT = datetime.fromtimestamp(timestamp)
            # 参数检查
            form = BetForm().fromMsg(msg).checkValid()
            # 检查时间
            if self.startTime and nowDT < self.startTime:
                raise TYBizException(-1, '活动还未开始')

            if self.endTime and nowDT >= self.endTime:
                raise TYBizException(-1, '活动已经结束')

            if self.stopBetTime and nowDT >= self.stopBetTime:
                raise TYBizException(-1, self._serverConf['stopBetDesc'])

            form.clientId = form.clientId or sessiondata.getClientId(form.userId)
            bet = self._serverConf[self.BET_KEYS[form.bet]]
            chip, status = self.bet(form.gameId, form.userId, form.clientId, form.target, bet['amount'], timestamp)
            return self.buildBetResponse(form.gameId, status, chip, form.target)
        except TYBizException, e:
            return {'ec': e.errorCode, 'info': e.message}
Example #50
0
 def makeVipInfoResponse(cls, gameId, userVip, vipGiftStates, clientId=None):
     expDesc = cls.buildExpDesc(userVip)
     clientId = clientId or sessiondata.getClientId(userVip.userId)
     mo = MsgPack()
     mo.setCmd('newvip')
     mo.setResult('action', 'vipInfo')
     mo.setResult('gameId', gameId)
     mo.setResult('userId', userVip.userId)
     mo.setResult('vipLevel', userVip.vipLevel.level)
     mo.setResult('vipExpDesc', expDesc)
     mo.setResult('tasks', cls.buildUpLevelTodoTasks(gameId, userVip, clientId))
     if len(vipGiftStates) > 0 and vipGiftStates[0].vipLevel.level == 0:
         del vipGiftStates[0]
     if userVip.vipLevel.nextVipLevel:
         vipGiftStates.append(TYVipGiftState(userVip.vipLevel.nextVipLevel, TYVipGiftState.STATE_UNGOT))
         if userVip.vipLevel.level == 0 and userVip.vipLevel.nextVipLevel.nextVipLevel:
             vipGiftStates.append(
                 TYVipGiftState(userVip.vipLevel.nextVipLevel.nextVipLevel, TYVipGiftState.STATE_UNGOT))
     vipInfoList = []
     for vipGiftState in vipGiftStates:
         vipInfoList.append(cls.buildVipLevelStateInfo(userVip, vipGiftState))
     mo.setResult('vipInfoList', vipInfoList)
     return mo
Example #51
0
    def doQuickBuyGetInfo(self, gameId, userId):
        clientId = sessiondata.getClientId(userId)
        toStoreTodotask = TodoTaskGotoShop('coin')
        if hallstore.storeSystem.isCloseLastBuy(clientId):
            TodoTaskHelper.sendTodoTask(gameId, userId, toStoreTodotask)
            return

        lastBuyProduct, _lastBuyClientId = hallstore.storeSystem.getLastBuyProduct(gameId, userId)
        if (not lastBuyProduct
            or not lastBuyProduct.recordLastBuy
            or not hallstore.storeSystem.canBuyProduct(gameId, userId, clientId, lastBuyProduct, 1)):
            if hallstore.storeSystem.lastBuyConf.payOrder:
                product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId,
                                                             hallstore.storeSystem.lastBuyConf.payOrder)
                if product:
                    payOrderTodoTask = TodoTaskPayOrder(product)
                    desc = strutil.replaceParams(hallstore.storeSystem.lastBuyConf.desc2,
                                                 {'product.displayName': product.displayName,
                                                  'product.price': product.price})
                    popInfoTodoTask = TodoTaskShowInfo(desc, True)
                    popInfoTodoTask.setSubCmd(payOrderTodoTask)
                    TodoTaskHelper.sendTodoTask(gameId, userId, popInfoTodoTask)
                    return
            TodoTaskHelper.sendTodoTask(gameId, userId, toStoreTodotask)
            return

        payOrderTodoTask = TodoTaskPayOrder(lastBuyProduct)
        desc = strutil.replaceParams(hallstore.storeSystem.lastBuyConf.desc,
                                     {'product.displayName': lastBuyProduct.displayName,
                                      'product.price': lastBuyProduct.price})
        popInfoTodoTask = TodoTaskShowInfo(desc, True)
        popInfoTodoTask.setSubCmd(payOrderTodoTask)
        popInfoTodoTask.setSubText(hallstore.storeSystem.lastBuyConf.subText)

        popInfoTodoTask.setSubCmdExt(toStoreTodotask)
        popInfoTodoTask.setSubTextExt(hallstore.storeSystem.lastBuyConf.subTextExt)
        TodoTaskHelper.sendTodoTask(gameId, userId, popInfoTodoTask)
Example #52
0
def sendWeixinRedEnvelope(gameId, userId, itemId, amount):
    clientId = sessiondata.getClientId(userId)
    defaultErrorInfo = '打开红包失败,请稍后再试'
    params = {
        'gameId': gameId,
        'userId': userId,
        'amount': amount,
        'wxappid': hall_wxappid.queryWXAppid(gameId, userId, clientId),
    }

    # TODO
    response = _requestSdk('/open/v4/user/act/wx/sendHBToUser', params, True)
    ftlog.debug('sdkclient.sendWeixinRedEnvelope gameId=', gameId,
                'userId=', userId,
                'itemId=', itemId,
                'amount=', amount,
                'response=', response)
    result = response.get('result') if response else None
    if not result:
        return -1, defaultErrorInfo
    ec = result.get('code', 0)
    if ec == 0:
        return 0, None
    return ec, result.get('info') or defaultErrorInfo
Example #53
0
    def get_award(self, uid):
        if not self.checkOperative():
            return 'acitivity expired!'

        actkey = ACTIVITY_KEY.format(HALL_GAMEID, uid, self.getid())
        weekcnt, daycnt = self._get_click_cnt(uid, actkey)
        if weekcnt >= self._clientConf['config']['weeklimit'] or daycnt >= self._clientConf['config']['daylimit']:
            return 'awardcnt:({},{}) expand limitcnt!'.format(weekcnt, daycnt)

        shareid = self._serverConf["share"]
        share = hallshare.findShare(shareid)
        if not share:
            return 'share:{} not exist!'.format(shareid)

        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_DAY_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_WEEK_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_TOTAL_CNT, 1)
        hallshare.sendReward(HALL_GAMEID, uid, share, 'share_click')
        # 分享BI日志汇报
        clientid = sessiondata.getClientId(uid)
        bireport.reportGameEvent('SHARE_CALLBACK', uid, HALL_GAMEID, shareid, 0, 0, 0, 0, 0, [], clientid)
        if share.mail:
            message.send(HALL_GAMEID, message.MESSAGE_TYPE_SYSTEM, uid, share.mail)
        return 'ok'
Example #54
0
    def getValidIdleSeatId(self, userId, seatIndex, result):
        '''通用坐下合法性检查函数
        
        Returns
            idleSeatId:
                >0   :  为新玩家找到合适座位,需要继续处理
                <0   :   断线重连
                0    :  坐下失败
         '''

        clientId = sessiondata.getClientId(userId)
        onlineSeatId = onlinedata.getOnlineLocSeatId(userId, self.table.roomId, self.table.tableId)
        if onlineSeatId and onlineSeatId <= self.maxSeatN:  # 断线重连, Note:旁观的人坐下此处不能返回负数,否则无法入座
            ftlog.hinfo('re-sit ok. |userId, tableId, seatId:', userId, self.tableId, onlineSeatId, caller=self)
            result["seatId"] = onlineSeatId
            result["reason"] = TYRoom.ENTER_ROOM_REASON_OK
            self.sendQuickStartRes(userId, clientId, result)
            return -onlineSeatId

        isOk, reason = self._checkSitCondition(userId)
        if not isOk:
            result["isOK"] = False
            result["reason"] = reason
            #             if reason == TYRoom.ENTER_ROOM_REASON_TABLE_FULL and userId in self.observers: #玩家从旁观状态点坐下排队,不下发quick_start
            if reason == TYRoom.ENTER_ROOM_REASON_TABLE_FULL:
                pass
            else:
                self.sendQuickStartRes(userId, clientId, result)
            return 0

        # 按指定座位坐下,如果座位上有人则随机分配座位。
        if seatIndex >= 0 and seatIndex < self.maxSeatN:
            if self.seats[seatIndex].isEmptySeat():
                return seatIndex + 1
            else:
                ftlog.warn("seatIndex >=0 but not self.seats[seatIndex].isEmptySeat()",
                           "|userId, roomId, tableId, seatIndex:", userId, self.table.roomId, self.table.tableId,
                           seatIndex,
                           caller=self)

        idleSeatId = self.findIdleSeat(userId)

        if idleSeatId < 0:
            # 断线重连机制出错了??
            # 已经在座位上坐下, 返回成功消息和桌子信息
            ftlog.warn("idleSeatId < 0",
                       "|userId, roomId, tableId, idleSeatId:", userId, self.table.roomId, self.table.tableId,
                       idleSeatId,
                       caller=self)
            result["seatId"] = abs(idleSeatId)
            result["reason"] = TYRoom.ENTER_ROOM_REASON_OK
            self.sendQuickStartRes(userId, clientId, result)
            return idleSeatId

        if idleSeatId == 0:  # 座位已经满了, 返回失败消息
            ftlog.warn("idleSeatId == 0",
                       "|userId, roomId, tableId, idleSeatId:", userId, self.table.roomId, self.table.tableId,
                       idleSeatId,
                       caller=self)
            result["isOK"] = False
            result["reason"] = TYRoom.ENTER_ROOM_REASON_TABLE_FULL
            if userId not in self.observers:  # 玩家从旁观状态点坐下排队,不下发quick_start
                self.sendQuickStartRes(userId, clientId, result)
            return 0

            # 为了支持并发坐下,findIdleSeat后不应该有异步操作
            # 座位冲突检查
        #         lastUserId = self.table.getLastSeatUserId(idleSeatId)
        #         if lastUserId and lastUserId != userId :
        #             ftlog.error(getMethodName(), 'seat Userid is not clean up !! tid=', self.table.tableId,
        #                         'seatId=', idleSeatId, 'olduid=', lastUserId, 'newuid=', userId)
        #             result["isOK"] = False
        #             result["reason"] = TYRoom.ENTER_ROOM_REASON_INNER_ERROR
        #             self.sendQuickStartRes(userId, clientId, result)
        #             return 0

        return idleSeatId
Example #55
0
 def getClientId(self, uid):
     if uid < 10000:
         clientId = "IOS_3.711_tyGuest.appStore.0-hall7.test.kuaile"
     else:
         clientId = sessiondata.getClientId(uid)
     return  clientId
Example #56
0
def doSendLedToUser(userId):
    global _ledClosesConf

    gameIdList = onlinedata.getGameEnterIds(userId)
    lastGameId = onlinedata.getLastGameId(userId)
    if not HALL_GAMEID in gameIdList:
        gameIdList.append(HALL_GAMEID)
    if not lastGameId in gameIdList:
        gameIdList.append(lastGameId)

    clientId = sessiondata.getClientId(userId)
    if clientId in _ledClosesConf:
        if ftlog.is_debug():
            ftlog.debug('hallled.doSendLedToUser clientId:', clientId, ' is in closes list:', _ledClosesConf, ' return')
        return

    gameIdInClientId = strutil.getGameIdFromHallClientId(clientId)
    if not gameIdInClientId in gameIdList:
        gameIdList.append(gameIdInClientId)

    if ftlog.is_debug():
        ftlog.debug('hallled.doSendLedToUser userId=', userId,
                    'gameIdList=', gameIdList,
                    'clientId=', clientId,
                    'gameIdInClientId=', gameIdInClientId,
                    'lastGameId=', lastGameId)

    _, clientVer, _ = strutil.parseClientId(clientId)
    for gameId in gameIdList:
        try:
            leds = getLedMsgList(gameId)
            if ftlog.is_debug():
                ftlog.debug('hallled.doSendLedToUser gameId=', gameId,
                            'userId=', userId,
                            'clientId=', clientId,
                            'leds=', leds)
            if leds:
                for led in leds:
                    msgDict = led[2]
                    if clientVer >= 3.6:
                        mo = MsgPack()
                        mo.setCmd('led')
                        for k, v in msgDict.iteritems():
                            mo.setResult(k, v)
                        mo.setResult('scope', led[3])
                    else:
                        mo = MsgPack()
                        mo.setCmd('led')
                        if gameId in (1, 8):
                            msgDictV2 = translateToMsgDictV2(msgDict)
                            if msgDictV2:
                                mo.setKey('richText', msgDictV2.get('richText'))
                        msgV1 = translateToMsgDictV1(msgDict)
                        if msgV1:
                            gameId = msgDict.get('gameId', led[1])
                            mo.setKey('result', [[led[0], gameId, msgV1]])

                    # 过滤LED
                    clientIdFilter = led[4]
                    if len(clientIdFilter) == 0 or clientId in clientIdFilter:
                        if ftlog.is_debug():
                            ftlog.debug('sendLed to user='******'msg=', mo)
                        router.sendToUser(mo, userId)
        except:
            ftlog.error("error leds:", leds)
Example #57
0
def getShareReward(gameId, userId, share, shareLoc, timestamp):
    '''
    给用户发放分享奖励
    '''
    # 分享BI日志汇报
    clientId = sessiondata.getClientId(userId)
    bireport.reportGameEvent('SHARE_CALLBACK', userId, gameId, share.shareId, 0, 0, 0, 0, 0, [], clientId)

    # 记录分享次数
    gamedata.incrGameAttr(userId, HALL_GAMEID, 'shareCount', 1)
    TGHall.getEventBus().publishEvent(HallShareEvent(gameId, userId, share.shareId, shareLoc))

    # 首先处理 分享相关的通知
    notifyInfoStr = pkgamedata.getGameAttr(userId, HALL_GAMEID, 'shareInfo')
    newInfo = {}
    pkgamedata.setGameAttr(userId, HALL_GAMEID, 'shareInfo', json.dumps(newInfo))

    if notifyInfoStr:
        notifyInfo = json.loads(notifyInfoStr)
        shareId = notifyInfo.get('shareId', 0)
        if shareId == share.shareId:
            # 通知
            info = notifyInfo.get('info', '')
            module = notifyInfo.get('module', '')
            if module == hall_red_envelope.TYRedEnvelope.EVENTID:
                hall_red_envelope.TYRedEnvelopeMgr.changeRedEnvelopeState(info,
                                                                          hall_red_envelope.TYRedEnvelope.STATE_SHARED)

                from poker.entity.game.game import TYGame
                clientId = sessiondata.getClientId(userId)
                gameids = hallconf.getDaShiFenFilter(clientId)
                for gid in gameids:
                    TYGame(gid).sendTuyooRedEnvelopeCallBack(userId, clientId, info)

    # 分享奖励
    ok, rewardCount = incrRewardCount(userId, share, timestamp)
    if not ok:
        if ftlog.is_debug():
            ftlog.debug('hallshare.getShareReward already no share, check update share promote ...')
            ftlog.debug('hallshare.getShareReward fail gameId=', gameId,
                        'userId=', userId,
                        'shareId=', share.shareId,
                        'shareLoc=', shareLoc,
                        'rewardCount=', rewardCount,
                        'maxRewardCount=', share.maxRewardCount)
        return False

    assetList = sendReward(gameId, userId, share, shareLoc)
    if assetList and share.mail:
        TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskGoldRain(share.mail))

    ftlog.debug('hallshare.getShareReward ok gameId=', gameId,
                'userId=', userId,
                'shareId=', share.shareId,
                'shareLoc=', shareLoc,
                'rewardCount=', rewardCount,
                'maxRewardCount=', share.maxRewardCount,
                'reward=', [(at[0].kindId, at[1]) for at in assetList] if assetList else [])
    if share.mail:
        pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, share.mail)
    # udpate free & promotion_loc
    datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc'])
    return True
Example #58
0
 def doStoreConfigUpdateV3_5(self, gameId, userId):
     clientId = sessiondata.getClientId(userId)
     router.sendToUser(StoreHelper.makeStoreConfigResponseV3_5(gameId, userId, clientId), userId)
Example #59
0
 def consumeRooCardsSecondWay(self, table, needRoomCardN):
     gameId = table.gameId
     userId = table.firstPlayerId
     clientId = sessiondata.getClientId(userId)
     self.consumeRoomCard(gameId, userId, needRoomCardN, clientId)
     table.consumedRoomCardN += needRoomCardN
def doOldRemoteCallNew(userId, msgline):
    '''
    必须要返回dict的实例
    '''
    try:
        ftlog.debug('doOldRemoteCallNew->msgline=', msgline)

        msg = MsgPack()
        msg.unpack(msgline)
        action = msg.getAction()
        gameId = msg.getParam('gameId', -1)
        userId = msg.getParam('userId', -1)
        userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
        clientId = sessiondata.getClientId(userId)
        if pkgamedata.setnxGameAttr(userId, HALL_GAMEID, 'flag.item.trans', 1) == 1:
            hallitem._tranformItems(gameId, userId, clientId, userBag)

        mo = MsgPack()
        mo.setResult('action', action)
        if action == 'getUserItem':
            kindId = msg.getParam('itemId', -1)
            val = getUserItem(userId, gameId, kindId, userBag)
            mo.setResult('item', val)

        elif action == 'getUserItemList':
            result = getUserItemList(userId, gameId, userBag)
            mo.setResult('item', result)

        elif action == 'addUserItem':
            kindId = msg.getParam('itemId', -1)
            count = msg.getParam('count', -1)
            eventId = msg.getParam('eventId', -1)
            eventId = eventIdToString(eventId)
            ftlog.debug('addUserItem itemId=', kindId, 'count=', count, 'eventId=', eventId)
            val = addUserItem(userId, gameId, kindId, count, eventId, userBag)
            mo.setResult('item', val)

        elif action == 'addUserItems':
            pass
        elif action == 'consumeUserItem':
            kindId = msg.getParam('itemId', -1)
            count = msg.getParam('count', -1)
            eventId = msg.getParam('eventId', -1)
            eventId = eventIdToString(eventId)
            ftlog.debug('consumeUserItem itemId=', kindId, 'count=', count, 'eventId=', eventId)
            val = consumeUserItem(userId, gameId, kindId, count, eventId, userBag)
            mo.setResult('item', val)
        elif action == 'useUserItem':
            kindId = msg.getParam('itemId', -1)
            val = useUserItem(userId, gameId, kindId, userBag)
            mo.setResult('item', val)
        elif action == 'updateTimingUserItems':
            isDayFirst = msg.getParam('isDayFirst', False)
            val = updateTimingUserItems(userId, gameId, isDayFirst, userBag)
            mo.setResult('item', val)
        elif action == 'loadUserDecroation':
            val = loadUserDecroation(userId, gameId, userBag)
            mo.setResult('item', val)
        else:
            ftlog.error('doOldRemoteCallNew unknown rpc action action=', action, 'gameId=', gameId, 'userId=', userId)

        ftlog.debug('doOldRemoteCallNew->mo=', mo._ht)
        mo.setResult('code', 0)
        return mo._ht
    except TYItemException:
        mo = MsgPack()
        mo.setResult('code', -1)
        return mo._ht
    except:
        ftlog.error()
        mo = MsgPack()
        mo.setResult('code', -1)
        return mo._ht