Exemplo n.º 1
0
Arquivo: gm.py Projeto: zhaozw/hall37
    def _do_http_gm_table_detail(self, gameId, httpRequest, httpArgs, httpResult):
        '''获取某牌桌的详情'''

        roomId = int(httpArgs['roomId'])
        tableId = int(httpArgs['tableId'])
        username = httpArgs.get('username')
        password = httpArgs.get('password')
        if username and password:
            token = daobase.executeMixCmd('HGET', '8:gm:token', username) == password
        else:
            token = False

        ftlog.info('GM._do_http_gm_table_detail << |',
                   'roomId, tableId, username, token', roomId, tableId, username, token)

        msg = utils.updateMsg(cmd='table', params={
            'action': 'gm',
            'sa': 'tableDetail',
            'gameId': gameId,
            'roomId': roomId,
            'tableId': tableId,
            'token': token,
        })
        ret = strutil.loads(router.queryTableServer(msg, roomId))
        ftlog.debug('_do_http_gm_table_detail| roomId, tableId, ret:', roomId, tableId, ret)
        tableDetail = strutil.loads(router.queryTableServer(msg, roomId))['result']['tableDetail']
        httpResult['tableDetail'] = tableDetail
Exemplo n.º 2
0
def getInviteTasks(userId, actionType):
    weakDatas = weakdata.getDayFishDataAll(userId, FISH_GAMEID)
    taskConfs_ = config.getInviteTasks(actionType)
    taskConfs = taskConfs_.values()
    taskConfs = sorted(taskConfs, key=lambda data: data["Id"])
    if actionType == NewPlayerAction:
        taskState = strutil.loads(weakDatas.get("inviteTasks", "[]"))
        playerNums = len(strutil.loads(weakDatas.get("inviteNewPlayers", "[]")))

    else:
        taskState = strutil.loads(weakDatas.get("recallTasks", "[]"))
        playerNums = len(strutil.loads(weakDatas.get("recallPlayers", "[]")))

    taskStartIndex = len(taskState) / OneGroupNum * OneGroupNum
    taskStartIndex = min((len(taskConfs) / OneGroupNum - 1) * OneGroupNum, taskStartIndex)

    # 奖励
    taskInfos = []
    tipsTaskIds = []
    for m in range(taskStartIndex, taskStartIndex + 5):
        if m >= len(taskConfs):
            break
        taskConf = taskConfs[m]
        taskId = taskConf["Id"]
        taskInfo = {}
        taskInfo["Id"] = taskId
        rewards = []
        for _reward in taskConf["rewards"]:
            rewardMap = {}
            kindId = _reward["name"]
            rewardMap["name"] = kindId
            rewardMap["count"] = _reward["count"]
            rewardMap["info"] = {}
            if util.isChestRewardId(kindId):
                rewardMap["info"] = chest_system.getChestInfo(kindId)
            rewards.append(rewardMap)
        taskInfo["rewards"] = rewards
        taskInfo["target"] = taskConf["target"]
        state = 0
        if taskId in taskState:
            state = 2
        elif playerNums >= taskConf["target"]:
            tipsTaskIds.append(taskId)
            state = 1
        taskInfo["state"] = state
        taskInfos.append(taskInfo)

    module_tip.resetModuleTip(userId, "invitetasks")
    if tipsTaskIds:
        module_tip.addModuleTipEvent(userId, "invitetasks", tipsTaskIds)
    return taskInfos, playerNums
Exemplo n.º 3
0
def _saveUserToRedis(userId, status, behaviourConf):
    if not userdata.checkUserData(userId):
        return False

    if not _checkExpectedUser(userId, behaviourConf):
        return False

    todayDate = int(dizhu_util.calcTodayIssueNum())
    behaviourInfo = {'type': BEHAVIOUR_TYPE_NONE, 'date': todayDate}
    try:
        ret = daobase.executeUserCmd(userId, 'HGET',
                                     'userBehaviour:6:' + str(userId), 'info')
        if ret:
            ret = strutil.loads(ret)
            behaviourType = ret.get('type', BEHAVIOUR_TYPE_NONE)
            if behaviourType not in [
                    BEHAVIOUR_TYPE_REWARDED, BEHAVIOUR_TYPE_NOUSEED
            ]:
                behaviourInfo['type'] = random.randrange(
                    1, 3, 1) if status == '0' else BEHAVIOUR_TYPE_NONE
                return daobase.executeUserCmd(userId, 'HSET',
                                              'userBehaviour:6:' + str(userId),
                                              'info',
                                              strutil.dumps(behaviourInfo))
        else:
            behaviourInfo['type'] = random.randrange(
                1, 3, 1) if status == '0' else BEHAVIOUR_TYPE_NONE
            return daobase.executeUserCmd(userId, 'HSET',
                                          'userBehaviour:6:' + str(userId),
                                          'info', strutil.dumps(behaviourInfo))
    except Exception, e:
        ftlog.warn('dizhu_user_behaviour._saveUserToRedis userId=', userId,
                   'err=', e)
Exemplo n.º 4
0
def getUserGamePlayTimes(userId):
    '''
    获取用户当游戏总局数
    '''
    winrate = gamedata.getGameAttrs(userId, 6, ['winrate'])
    winrate = strutil.loads(winrate[0], ignoreException=True, execptionValue={'pt': 0, 'wt': 0})
    return winrate.get('pt', 0)
Exemplo n.º 5
0
def returnSignInfFees(userId, roomId, fees):
    #获取用户报名券信息
    roomId = gdata.getBigRoomId(roomId)
    jstr = daobase.executeRePlayCmd('hget', 'match:discount:6', userId)
    match_discounts = strutil.loads(jstr) if jstr else []
    if match_discounts:
        for discount in match_discounts:
            itemId = discount.get('itemId', '')
            matchId = discount.get('matchId', '')
            if matchId == roomId:
                for fee in fees:
                    if fee['itemId'] == ASSET_DIAMOND_KIND_ID:
                        discounted = 10
                        lottery_conf = dizhuconf.getMatchLotteryConf()
                        discountItems = lottery_conf.get('discountItem')
                        for discountItem in discountItems:
                            if itemId == discountItem.get('itemId', ''):
                                discounted = discountItem.get('discount', 10)

                        fee['count'] = fee['count'] * discounted / 10
                        fees.append({'itemId':itemId, 'count':1})
                        delMatchLotteryInfo(userId, roomId)
                break
    ftlog.debug('returnSignInfFees userId=', userId, 'roomId=', roomId, 'fees=', fees, 'match_discounts=', match_discounts)
    return fees
Exemplo n.º 6
0
    def onGameRoundFinish(cls, event):
        banConf = cls.getMatchBanConf()
        if not banConf.get("open"):
            return

        if ftlog.is_debug():
            ftlog.debug('BanHelper.onGameRoundFinish',
                        'tableId=', event.table.tableId,
                        'seats=', [(s.userId, s.seatId, s.status.isPunish, s.player.isQuit) for s in event.table.seats])
        for seat in event.table.seats:
            if hasattr(seat.player, 'mixId') and seat.player.mixId:
                roomId = int(seat.player.mixId)
            else:
                roomId = event.table.bigRoomId

            if seat.status.isTuoguan and not seat.player.isQuit and roomId in banConf.get('fromRooms', []):
                matchTuoguan = gamedata.getGameAttr(seat.userId, DIZHU_GAMEID, 'matchTuoguanCount')
                matchTuoguan = strutil.loads(matchTuoguan) if matchTuoguan else {}

                # 自然日清零
                currentTimestamp = pktimestamp.getCurrentTimestamp()
                if not pktimestamp.is_same_day(currentTimestamp, matchTuoguan.get('expired', pktimestamp.getCurrentTimestamp())):
                    matchTuoguan['expired'] = pktimestamp.getCurrentTimestamp()
                    matchTuoguan['count'] = 0

                if matchTuoguan.get('count'):
                    matchTuoguan['count'] += 1
                else:
                    matchTuoguan['count'] = 1

                banTime = cls.getTuoguanBanTime(matchTuoguan['count'], banConf)
                if banTime:
                    matchTuoguan['expired'] = banTime * 60 + pktimestamp.getCurrentTimestamp()
                gamedata.setGameAttr(seat.userId, DIZHU_GAMEID, 'matchTuoguanCount', strutil.dumps(matchTuoguan))
Exemplo n.º 7
0
def check(self, gameId, userId, clientId, timestamp, **kwargs):
    # 新用户不属于A
    if self.newUserCond.check(gameId, userId, clientId, timestamp):
        return False

    behaviourInfo = daobase.executeUserCmd(
        userId, 'hget', 'userBehaviour:%s:%s' % (self.gameId, userId), 'info')
    if not behaviourInfo:
        return True

    try:
        behaviourInfo = strutil.loads(behaviourInfo)
    except:
        return False

    infoType = behaviourInfo.get('type', 0)

    if infoType == 1:
        return True

    if infoType == 0:
        todayDate = datetime.fromtimestamp(timestamp).strftime('%Y%m%d')
        if str(behaviourInfo.get('date')) != todayDate:
            return True

    return False
Exemplo n.º 8
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)
Exemplo n.º 9
0
def _getTcTemplates(moduleKey, funDecode):
    # 取得redis中的所有原始数据
    datas = {}
    xkey = 'game:%s:' + moduleKey + ':' + CLIENT_ID_TEMPLATE
    for gid in getConfigGameIds():
        subdata = ftcon.getConfNoCache('GET', xkey % (gid))
        if subdata:
            subdata = strutil.loads(subdata)
            for k, d in subdata.items():
                if not k in datas:
                    if isinstance(d, dict):
                        datas[k] = {}
                    else:
                        datas[k] = []
                if isinstance(d, dict):
                    datas[k].update(d)
                elif isinstance(d, list):
                    datas[k].extend(d)
                else:
                    datas[k] = d
    datas = strutil.replaceObjRefValue(datas)
    if funDecode:
        cachedata = funDecode(moduleKey, datas)
        assert (isinstance(cachedata, dict)), 'the cache templates data must be a dict !' + str(
            moduleKey) + ' funDecode=' + str(funDecode)
    else:
        cachedata = datas['templates']
    _templatesCache[moduleKey] = cachedata

    return cachedata
Exemplo n.º 10
0
def loadUserQuizStatus(gameId, userId, actId):
    jstr = daobase.executeUserCmd(userId, 'hget',
                                  'act:%s:%s' % (gameId, userId), actId)
    if jstr:
        d = strutil.loads(jstr)
        return UserQuizStatus(userId).fromDict(d)
    return None
Exemplo n.º 11
0
def attachment_receive(userid, typeid, msgid, itemsystem):
    """
    收取附件的物品或者货币
    @param itemsystem: poker.entity.biz.item.TYItemSystem
    @param typeid: 类型, L{message.MESSAGE_TYPES}
    @param userid:
    @param msgid: 消息id
    @return:
    """
    rediskey = REDIS_KEY.format(typeid, HALL_GAMEID, userid)
    data = daobase.executeUserCmd(userid, 'HGET', rediskey, msgid)
    if not data:
        ftlog.debug('message.attachment_receive msg not exsit,uid=', userid,
                    'tid=', typeid, 'msgid=', msgid)
        return

    msg = strutil.loads(data)
    attach = msg.get('attachment')
    if not attach or attach.get('typeid') != AttachmentAsset.TYPE_ID:
        ftlog.debug('message.attachment_receive no asset,uid=', userid, 'tid=',
                    typeid, 'msgid=', msgid)
        return

    daobase.executeUserCmd(userid, 'HDEL', rediskey, msgid)
    asset = AttachmentAsset()
    asset.unmarshal(attach)
    ua = itemsystem.loadUserAssets(userid)
    gameid = msg.get('gameid')
    return gameid, ua.sendContentItemList(gameid, asset.itemlist, 1, True,
                                          timestamp.getCurrentTimestamp(),
                                          asset.eventid, asset.eventparam)
Exemplo n.º 12
0
 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)
Exemplo n.º 13
0
def initRobotSetting():
    global RESOURCE_ROBOTS
    
    if len(RESOURCE_ROBOTS) == 0:
        res = loadResource('robot_info.json')
        rinfo = strutil.loads(res)
        RESOURCE_ROBOTS = rinfo['robots']
Exemplo n.º 14
0
def convertOldData(gameId, userId):
    """
    大厅v3.9存储改动,user数据库:
    键message:g(gameid)u(userid),废弃
    键msg:(gameId):(toUid),废弃
    """
    oldkey = 'message:g{}u{}'.format(gameId, userId)
    daobase.executeUserCmd(userId, 'DEL', oldkey)

    # from datetime import datetime
    # sendPrivate(9999, 10004, 0, 'oldmsg test now:{}'.format(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')))
    hall37key = 'msg:{}:{}'.format(gameId, userId)
    rediskey = REDIS_KEY.format(MESSAGE_TYPE_PRIVATE, HALL_GAMEID, userId)
    new_msg_len = daobase.executeUserCmd(userId, 'HLEN', rediskey)  # 限制50条
    datas = daobase.executeUserCmd(userId, 'LRANGE', hall37key, 0,
                                   MAX_SIZE - new_msg_len - 1)
    if datas:
        for msgstr in datas:
            msg = strutil.loads(msgstr, ignoreException=True)
            if msg:
                new_msg = {
                    'gameid': gameId,
                    'time': msg['time'],
                    'text': msg['msg']
                }
                if msg['from'] > 0:
                    new_msg['from'] = msg['from']
                maxid = gamedata.incrGameAttr(userId, HALL_GAMEID,
                                              'msg.id.max', 1)
                daobase.executeUserCmd(userId, 'HSET', rediskey, maxid,
                                       strutil.dumps(new_msg))
    daobase.executeUserCmd(userId, 'DEL', hall37key)
Exemplo n.º 15
0
def sportlotteryBet(gameId, clientId, userId, date, matchId, party, coin):
    if coin <= 0:
        raise SportlotteryBadBetException()

    if party not in (1, 2, 3):
        raise SportlotteryBetPosErrorException()

    jstr = daobase.executeMixCmd('hget', leagueDaykey % date, matchId)
    leagueId = 0  #
    homewin = 0.0
    if jstr:
        j = strutil.loads(jstr)
        leagueId = int(j.get('leagueId', 0))
        homewin = float(j.get('odds', ['0', '0', '0'])[0])
        if j.get('status') not in BET_STATUS:
            raise SportlotteryForbidBetException()
    else:
        raise SportlotteryMatchOverException()

    homeBet = daobase.executeUserCmd(userId, 'hget', betHomeKey % userId,
                                     '%s:%s' % (date, matchId)) or 0
    aveBet = daobase.executeUserCmd(userId, 'hget', betAveKey % userId,
                                    '%s:%s' % (date, matchId)) or 0
    awayBet = daobase.executeUserCmd(userId, 'hget', betAwayKey % userId,
                                     '%s:%s' % (date, matchId)) or 0

    # 获取总金额
    totalBet = int(homeBet) + int(aveBet) + int(awayBet)
    if totalBet + coin > SportlotteryConf.totalBetLimit():
        tips = SportlotteryConf.totalBetLimitTips()
        if tips:
            raise SportlotteryBetOverLimitException(tips)
        raise SportlotteryBetOverLimitException()

    trueDelta, final = addChip(userId, gameId, clientId, -coin, leagueId,
                               homewin, party)

    if abs(trueDelta) < coin:
        raise SportlotteryChipNotEnoughException()

    if party == 1:
        daobase.executeUserCmd(userId, 'hincrby', betHomeKey % userId,
                               '%s:%s' % (date, matchId), coin)
    elif party == 2:
        daobase.executeUserCmd(userId, 'hincrby', betAveKey % userId,
                               '%s:%s' % (date, matchId), coin)
    elif party == 3:
        daobase.executeUserCmd(userId, 'hincrby', betAwayKey % userId,
                               '%s:%s' % (date, matchId), coin)
    else:
        raise SportlotteryBetPosErrorException()

    # 联赛下注总人数
    daobase.executeMixCmd('sadd', leagueBetPlayersKey % (date, matchId),
                          userId)
    # 联赛下注总钱数
    daobase.executeMixCmd('hincrby', leagueBetChipsKey % (date, matchId),
                          party, coin)

    return final
Exemplo n.º 16
0
 def _check_param_params(self, key, params):
     try:
         jstr = runhttp.getParamStr(key)
         params = strutil.loads(jstr)
         return None, params
     except:
         return 'the jsonstr params is not a list Format !!', None
Exemplo n.º 17
0
    def doPutMessage(self, gameId, fromUid, toUid, mtype, msg, ismgr, scope,
                     clientIds):
        button = runhttp.getParamStr('button', None)
        button = strutil.loads(button, ignoreException=True)
        data = None
        mo = MsgPack()

        if mtype == 0 and len(msg) > 0 and toUid > 0 and gameId >= 0:
            # 发送私人消息
            # 必须参数
            # 1)msg - 消息
            # 2)toUid - 接收消息的userId
            # 3)gameId
            data = pkmessage.sendPrivate(gameId, toUid, fromUid, msg, button)
        elif mtype == 1 and len(msg) > 0 and gameId >= 0:
            # 发送站内消息到全体用户
            # 必选参数
            # msg - 消息
            # gameId
            data = pkmessage.sendGlobal(gameId, msg, button)
        elif mtype == 2 and gameId > 0 and len(msg) > 0:
            # 发送LED
            # TODO 当前Game服务为4,5,6号 , 每个服务都发送
            mo.setCmd('send_led')
            mo.setParam('msg', msg)
            mo.setParam('gameId', gameId)
            mo.setParam('ismgr', 1)
            router.sendToAll(mo, gdata.SRV_TYPE_UTIL)
            data = True
        elif mtype == 3 and gameId > 0 and toUid > 0 and len(msg) > 0:
            # 封装popwnd
            # 必选参数
            # gameId
            # toUid 接收弹窗的userId
            # msg 弹窗消息内容
            task = TodoTaskShowInfo(msg, True)
            mo = TodoTaskHelper.makeTodoTaskMsg(gameId, toUid, task)
            # 将消息发送给此人
            router.sendToUser(mo, toUid)
            data = True
        elif mtype == 4 and gameId > 0 and len(msg) > 0 and len(scope) > 0:
            mo.setCmd('send_led')
            mo.setParam('msg', msg)
            ftlog.info('send_led new msg=', msg)
            mo.setParam('gameId', gameId)
            ftlog.info('send_led new gameId=', gameId)
            mo.setParam('ismgr', ismgr)
            ftlog.info('send_led new ismgr=', ismgr)
            mo.setParam('scope', scope)
            ftlog.info('send_led new scope=', scope)
            mo.setParam('clientIds', clientIds)
            ftlog.info('send_led new clientIds=', clientIds)
            router.sendToAll(mo, gdata.SRV_TYPE_UTIL)
            data = True

        if data == None:
            mo.setError(1, 'params error')
        else:
            mo.setResult('ok', 'true')
        return mo
Exemplo n.º 18
0
def saveVideoDataToHttp(userId, gameRound):
    # 调用http
    videoId = '%s_%s' % (userId, gameRound.roundId)
    url = '%s/dizhu/tupt/replay/video/save?videoId=%s' % (gdata.httpGame(), videoId)
    gameRoundDict = GameRoundCodecDictReplay().encode(gameRound)
    gameRoundDict['uid'] = userId

    if ftlog.is_debug():
        ftlog.debug('obsystem.saveVideoDataToHttp userId=', userId,
                    'videoId=', videoId,
                    'url=', url,
                    'gameRoundDict=', gameRoundDict)

    response = None
    try:
        _, response = http.runHttp('POST', url, None, strutil.dumps(gameRoundDict), 3, 6)
        datas = strutil.loads(response)
        ec = datas.get('ec', 0)
        if ec == 0:
            return videoId
        raise TYBizException(ec, datas.get('info', ''))
    except TYBizException:
        raise
    except:
        ftlog.error(url, 'response=', response)
        raise TYBizException(-1, '保存失败')
Exemplo n.º 19
0
def sportlotteryLove(userId, date, matchId, love):
    jstr = daobase.executeMixCmd('hget', leagueDaykey % date, matchId)
    if jstr:
        j = strutil.loads(jstr)
        if j['status'] not in BET_STATUS:
            raise SportlotteryForbidBetException()
    else:
        raise SportlotteryMatchOverException()

    if love == 0:
        if 1 == daobase.executeMixCmd('sismember',
                                      playerLovesHomeKey % (date, matchId),
                                      userId):
            return -1, '已经点过赞了'
        else:
            daobase.executeMixCmd('sadd', playerLovesHomeKey % (date, matchId),
                                  userId)

    elif love == 1:
        if 1 == daobase.executeMixCmd('sismember',
                                      playerLovesAwayKey % (date, matchId),
                                      userId):
            return -1, '已经点过赞了'
        else:
            daobase.executeMixCmd('sadd', playerLovesAwayKey % (date, matchId),
                                  userId)

    else:
        raise SportlotteryLovePosErrorException()

    return 0, '点赞成功'
Exemplo n.º 20
0
    def loadData(self):
        ''' 加载用户活跃度数据 '''
        expireDay, expireWeek = False, False
        jstr = daobase.executeUserCmd(
            self.userId, 'hget', 'actwx:%s:%s' % (DIZHU_GAMEID, self.userId),
            'active')
        if jstr:
            jdict = strutil.loads(jstr)
            userActiveData = self.decodeFromDict(jdict)
        else:
            userActiveData = self

        # 数据刷新
        if not userActiveData.activeDataWeek:
            userActiveData.activeDataWeek = ActiveDataWeek().decodeFromDict({})
        if not userActiveData.activeDataDay:
            userActiveData.activeDataDay = ActiveDataDay().decodeFromDict({})

        currentTimestamp = pktimestamp.getCurrentTimestamp()
        if not pktimestamp.is_same_week(
                userActiveData.activeDataWeek.timestamp, currentTimestamp):
            expireWeek = True
            userActiveData.activeDataWeek = ActiveDataWeek().decodeFromDict({})
            userActiveData.activeDataDay = ActiveDataDay().decodeFromDict({})
        if not pktimestamp.is_same_day(userActiveData.activeDataDay.timestamp,
                                       currentTimestamp):
            expireDay = True
            userActiveData.activeDataDay = ActiveDataDay().decodeFromDict({})

        if ftlog.is_debug():
            ftlog.debug('UserActiveData.loadData userId=',
                        userActiveData.userId, 'expireDay=', expireDay,
                        'expireWeek=', expireWeek, 'originDataStr=', jstr,
                        'data=', userActiveData.toDict())
        return userActiveData, expireDay, expireWeek
Exemplo n.º 21
0
def initRobotSetting():
    global RESOURCE_ROBOTS

    if len(RESOURCE_ROBOTS) == 0:
        res = loadResource('wx_users.json')
        rinfo = strutil.loads(res)
        RESOURCE_ROBOTS = rinfo['wx_users']
Exemplo n.º 22
0
def checkSetMedal(gameId, userId, baseScore, isGameStart, winchip):
    winchip = 0 if isGameStart else winchip

    winrate, oldLevel = gamedata.getGameAttrs(userId, gameId,
                                              ['winrate', 'level'], False)
    winrate = strutil.loads(winrate, ignoreException=True, execptionValue={})
    if winrate is None:
        winrate = {}
    if winchip >= 0 or isGameStart:
        _processGamePlayWinTimes(winrate, isGameStart)
    oldLevel = strutil.parseInts(oldLevel)
    deltaExp = 0
    if winchip > 0 or isGameStart:
        deltaExp = _calUserDetalExp(winchip, baseScore)

    exp = userdata.incrExp(userId, deltaExp)
    explevel, _ = gameexp.getLevelInfo(gameId, exp)
    gamedata.setGameAttrs(userId, gameId, ['winrate', 'level'],
                          [strutil.dumps(winrate), explevel])
    if oldLevel != explevel:
        TYGame(gameId).getEventBus().publishEvent(
            UserLevelGrowEvent(gameId, userId, oldLevel, explevel))
    if isGameStart:
        # 广告商通知
        pcount = commconf.getAdNotifyPlayCount(gameId)
        if pcount > 0 and winrate.get('pt', 0) == pcount:
            sdkclient.adNotifyCallBack(gameId, userId)
    return exp, deltaExp, winrate
Exemplo n.º 23
0
def getAllGuns(userId, mode):
    """
    获得所有皮肤炮数据
    """
    clientId = util.getClientId(userId)
    assert isinstance(userId, int) and userId > 0
    _key = _buildUserGunKey(userId, mode)
    value = daobase.executeUserCmd(userId, "HGETALL", _key)
    if value:
        gunInfos = {}
        savaData = []
        for index in xrange(0, len(value), 2):
            gunId = value[index]
            if gunId in config.getAllGunIds(clientId, mode):
                gunData = strutil.loads(value[index + 1], False, True)
                if len(gunData) <= 2:
                    gunConfig = config.getGunConf(gunId, clientId,
                                                  gunData[INDEX_LEVEL], mode)
                    gunData.append(gunConfig["skins"][0])
                    savaData.append(gunId)
                    savaData.append(strutil.dumps(gunData))
                gunInfos[gunId] = gunData

        if savaData:
            daobase.executeUserCmd(userId, "HMSET", _key, *savaData)
        return gunInfos
    return {}
Exemplo n.º 24
0
def loadStatus(userId, actId):
    jstr = daobase.executeUserCmd(userId, 'hget',
                                  'act:%s:%s' % (DIZHU_GAMEID, userId), actId)
    if jstr:
        d = strutil.loads(jstr)
        return SendPrizeStatus(userId).fromDict(d)
    return None
Exemplo n.º 25
0
def _getTcTemplates(moduleKey, funDecode):
    # 取得redis中的所有原始数据
    datas = {}
    xkey = 'game:%s:' + moduleKey + ':' + CLIENT_ID_TEMPLATE
    for gid in getConfigGameIds():
        subdata = ftcon.getConfNoCache('GET', xkey % (gid))
        if subdata:
            subdata = strutil.loads(subdata)
            for k, d in subdata.items():
                if not k in datas:
                    if isinstance(d, dict):
                        datas[k] = {}
                    else:
                        datas[k] = []
                if isinstance(d, dict):
                    datas[k].update(d)
                elif isinstance(d, list):
                    datas[k].extend(d)
                else:
                    datas[k] = d
    datas = strutil.replaceObjRefValue(datas)
    if funDecode:
        cachedata = funDecode(moduleKey, datas)
        assert (isinstance(
            cachedata,
            dict)), 'the cache templates data must be a dict !' + str(
                moduleKey) + ' funDecode=' + str(funDecode)
    else:
        cachedata = datas['templates']
    _templatesCache[moduleKey] = cachedata

    return cachedata
Exemplo n.º 26
0
def startSportlottery():
    global _sportlotteryMap
    now = datetime.datetime.now()
    for n in range(DAYS + 1):
        _afterday = (now + datetime.timedelta(days=n)).strftime('%Y-%m-%d')
        datas = daobase.executeMixCmd('hgetall', leagueDaykey % _afterday)
        if datas:
            for i in xrange(len(datas) / 2):
                matchId = datas[i * 2]

                if int(matchId) in _sportlotteryMap:
                    continue

                jstr = datas[i * 2 + 1]
                try:
                    d = strutil.loads(jstr)
                    sportObj = Sportlottery()
                    sportObj.fromDict(d)
                    sportObj.start()
                    _sportlotteryMap[sportObj.matchId] = sportObj

                    if ftlog.is_debug():
                        ftlog.debug('startSportlottery', 'sportObj=', sportObj)
                except:
                    ftlog.warn('hallsportlottery.startSportlottery',
                               'matchId=', matchId)

        if ftlog.is_debug():
            ftlog.debug('startSportlottery date',
                        'n=', n, '_sportlotteryMap key=',
                        _sportlotteryMap.keys(), 'datas=', datas)
Exemplo n.º 27
0
def sportlotteryGetReward(gameId, clientId, userId, date, matchId):
    jstr = daobase.executeUserCmd(userId, 'hget', waitRewardKey % userId,
                                  '%s:%s' % (date, matchId))
    if jstr:
        d = strutil.loads(jstr)
        betCoins = d['betCoins']
        odds = d['odds']
        delta = int(betCoins) * float(odds)
        leagueId = int(d.get('leagueId', 0))
        homewin = float(d.get('odds', ['0', '0', '0'])[0])
        betpos = _winResult.get(d.get('option', ''), 0)

        _, final = addChip(userId, gameId, clientId, int(delta), leagueId,
                           homewin, betpos)
        daobase.executeUserCmd(userId, 'hdel', waitRewardKey % userId,
                               '%s:%s' % (date, matchId))
        # 猜中
        d['rewardstatus'] = 4
        winLen = daobase.executeUserCmd(userId, 'rpush', winkey % userId,
                                        strutil.dumps(d))
        if winLen > 10:
            daobase.executeUserCmd(userId, 'ltrim', winkey % userId, -10, -1)

        return final
    else:
        raise SportlotteryBeGetRewardException()
Exemplo n.º 28
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)
Exemplo n.º 29
0
def _checkSetMedal(userId, roomMutil, basebet, basemulti, isGameStart,
                   winchip):
    winchip = 0 if isGameStart else winchip

    winrate, oldLevel = gamedata.getGameAttrs(userId, DIZHU_GAMEID,
                                              ['winrate', 'level'], False)
    winrate = strutil.loads(winrate, ignoreException=True, execptionValue={})
    if winchip >= 0 or isGameStart:
        _processGamePlayWinTimes(winrate, isGameStart)

    oldLevel = strutil.parseInts(oldLevel)
    detalExp = 0
    if winchip > 0 or isGameStart:
        detalExp = _calUserDetalExp(winchip, roomMutil, basebet, basemulti)
    exp = userdata.incrExp(userId, detalExp)
    explevel = dizhuaccount.getExpLevel(exp)

    gamedata.setGameAttrs(userId, DIZHU_GAMEID, ['winrate', 'level'],
                          [strutil.dumps(winrate), explevel])
    if oldLevel != explevel:
        from dizhu.game import TGDizhu
        TGDizhu.getEventBus().publishEvent(
            UserLevelGrowEvent(DIZHU_GAMEID, userId, oldLevel, explevel))
    if isGameStart:
        # 广告商通知
        pcount = dizhuconf.getAdNotifyPlayCount()
        if pcount > 0 and winrate.get('pt', 0) == pcount:
            sdkclient.adNotifyCallBack(DIZHU_GAMEID, userId)
    nextExp = dizhuaccount.getGameUserNextExp(explevel)
    title = dizhuaccount.getGameUserTitle(explevel)
    return [explevel, exp, detalExp, nextExp, title]
Exemplo n.º 30
0
def getGlobal(gameId, userId, pageNo=1):
    """
    已废弃,待删除
    取得当前用户的全局未读私信的内容
    """
    maxMsgId = daobase.executeMixCmd('HGET', 'msg',
                                     'msg.id.max.' + str(gameId))
    readMaxId = gamedata.getGameAttrs(userId, gameId, 'msg.id.global')
    rediskey = 'msg:' + str(gameId)

    maxMsgId, readMaxId = strutil.parseInts(maxMsgId, readMaxId)
    msglist = []
    maxId = readMaxId
    if pageNo < 1:
        pageNo = 1
    lstart = (pageNo - 1) * 20
    lend = lstart + 20 - 1
    datas = daobase.executeMixCmd('LRANGE', rediskey, lstart, lend)
    count = 0
    if datas:
        for msgstr in datas:
            msg = strutil.loads(msgstr, ignoreException=True)
            if msg:
                maxId = max(maxId, msg['id'])
                msglist.append(msg)
                count += 1
    if maxId > readMaxId:
        gamedata.setGameAttr(userId, gameId, 'msg.id.global', maxId)
    return {
        'count': count,
        'maxId': maxMsgId,
        'readId': readMaxId,
        'pageNo': pageNo,
        'list': msglist
    }
Exemplo n.º 31
0
    def doPutMessage(self, gameId, fromUid, toUid, mtype, msg, ismgr, scope, clientIds):
        button = runhttp.getParamStr('button', None)
        button = strutil.loads(button, ignoreException=True)
        data = None
        mo = MsgPack()

        if mtype == 0 and len(msg) > 0 and toUid > 0 and gameId >= 0:
            # 发送私人消息
            # 必须参数 
            # 1)msg - 消息
            # 2)toUid - 接收消息的userId
            # 3)gameId
            data = pkmessage.sendPrivate(gameId, toUid, fromUid, msg, button)
        elif mtype == 1 and len(msg) > 0 and gameId >= 0:
            # 发送站内消息到全体用户
            # 必选参数
            # msg - 消息
            # gameId
            data = pkmessage.sendGlobal(gameId, msg, button)
        elif mtype == 2 and gameId > 0 and len(msg) > 0:
            # 发送LED
            # TODO 当前Game服务为4,5,6号 , 每个服务都发送
            mo.setCmd('send_led')
            mo.setParam('msg', msg)
            mo.setParam('gameId', gameId)
            mo.setParam('ismgr', 1)
            router.sendToAll(mo, gdata.SRV_TYPE_UTIL)
            data = True
        elif mtype == 3 and gameId > 0 and toUid > 0 and len(msg) > 0:
            # 封装popwnd
            # 必选参数
            # gameId
            # toUid 接收弹窗的userId
            # msg 弹窗消息内容
            task = TodoTaskShowInfo(msg, True)
            mo = TodoTaskHelper.makeTodoTaskMsg(gameId, toUid, task)
            # 将消息发送给此人
            router.sendToUser(mo, toUid)
            data = True
        elif mtype == 4 and gameId > 0 and len(msg) > 0 and len(scope) > 0:
            mo.setCmd('send_led')
            mo.setParam('msg', msg)
            ftlog.info('send_led new msg=', msg)
            mo.setParam('gameId', gameId)
            ftlog.info('send_led new gameId=', gameId)
            mo.setParam('ismgr', ismgr)
            ftlog.info('send_led new ismgr=', ismgr)
            mo.setParam('scope', scope)
            ftlog.info('send_led new scope=', scope)
            mo.setParam('clientIds', clientIds)
            ftlog.info('send_led new clientIds=', clientIds)
            router.sendToAll(mo, gdata.SRV_TYPE_UTIL)
            data = True

        if data == None:
            mo.setError(1, 'params error')
        else:
            mo.setResult('ok', 'true')
        return mo
Exemplo n.º 32
0
def getStateAttrJson(uid, gameid, attrname, defaultVal=None):
    '''
    获取用户状态属性
    '''
    assert (isinstance(gameid, int) and gameid > 0), 'gameid must be int'
    value = getStateAttr(uid, gameid, attrname)
    value = strutil.loads(value, False, True, defaultVal)
    return value
Exemplo n.º 33
0
def getErdayiMatchStageList(matchingId3):
    key = 'erdayi:6:%s' % matchingId3
    jstr = daobase.executeRePlayCmd('hget', key, matchingId3)
    ret = strutil.loads(jstr) if jstr else None
    if ftlog.is_debug():
        ftlog.debug('getErdayiMatchStageList matchingId3=', matchingId3,
                    'ret=', ret)
    return ret
Exemplo n.º 34
0
def getGameAttrJson(uid, gameid, attrname, defaultVal=None):
    """
    获取用户游戏属性
    """
    assert (isinstance(gameid, int) and gameid > 0), 'gameid must be int'
    value = getGameAttr(uid, gameid, attrname)
    value = strutil.loads(value, False, True, defaultVal)
    return value
Exemplo n.º 35
0
def checkResponse(conf, response):
    d = strutil.loads(response)
    status = d.get('status', 0)
    if status == 0:
        password = d.get('data', {}).get('hongbao_code')
        if not password or not isstring(password):
            return -1, conf.get('errorInfo', '红包系统忙,请稍后再试')
        return 0, password
    return status, d.get('info') or conf.get('errorInfo', '红包系统忙,请稍后再试')
Exemplo n.º 36
0
def _requestSdk2(path, params, needresponse=False):
    url = '%s%s' % (gdata.httpSdkInner(), path)
    jsonstr, _ = webpage.webget(url, postdata_=params, needresponse=needresponse)
    if needresponse:
        try:
            return strutil.loads(jsonstr)
        except:
            ftlog.error('SDKURL=', url, 'PARAMS=', params)
    return None
Exemplo n.º 37
0
 def _check_param_hotparams(self, key, params):
     hotparams = runhttp.getParamStr(key, '')
     try:
         if len(hotparams) > 0:
             hotparams = strutil.loads(hotparams)
         return None, hotparams
     except:
         pass
     return 'param hotparams error, must be a json dumps string', None
Exemplo n.º 38
0
def _tryReadDataFromMySql(userId, intClientId, appId, ctfull):
    # 得到MySQL中的数据
    csize = getMysqlSize()
    dbname = 'user' + str(userId % csize)
    tablename = 't' + str(userId / csize % 200)
    sqlstr = 'select data from %s where userid=%d limit 1' % (tablename, userId)
    ftlog.info('_tryReadDataFromMySql', userId, intClientId, appId, dbname, sqlstr)
    jsonstr = dbmysql._queryMysql00(userId, dbname, sqlstr)
    ftlog.info('_tryReadDataFromMySql before', userId, jsonstr)
    if not jsonstr:
        ftlog.info('_tryReadDataFromMySql', userId, 'the user mysql data not found !')
        return 0
    loaddatas = strutil.loads(jsonstr)
    # 拆解执行数据装载,避免redis的slowlog, 避免挤压redis
    isok, chip, diamond, coin, coupon = 1, 0, 0, 0, 0
    rkeys = loaddatas.keys()
    while (len(rkeys)) > 0:
        subrkeys = rkeys[0:4]
        rkeys = rkeys[4:]
        subdata = {}
        for subkey in subrkeys:
            subdata[subkey] = loaddatas[subkey]
        jsonstr1 = strutil.dumps(subdata)
        isok1, chip1, diamond1, coin1, coupon1 = daobase.executeUserLua(userId,
                                                                        dataswap_scripts.DATA_SWAP_LUA_SCRIPT, 3,
                                                                        userId, ctfull, jsonstr1)
        ftlog.debug('_tryReadDataFromMySql save to redis->', userId, isok, jsonstr1)
        isok = min(isok, isok1)
        chip = max(chip, chip1)
        diamond = max(diamond, diamond1)
        coin = max(coin, coin1)
        coupon = max(coupon, coupon1)
    ftlog.info('_tryReadDataFromMySql save to redis->', userId,
               'isok=', isok, 'chip=', chip, 'diamond=', diamond,
               'coin=', coin, 'coupon=', coupon)
    chip, diamond, coin, coupon = strutil.parseInts(chip, diamond, coin, coupon)
    if isok == 1:
        from poker.entity.biz import bireport
        bireport.reportBiChip(userId, chip, chip, chip,
                              'DATA_FROM_MYSQL_2_REDIS_CHIP',
                              intClientId, appId, appId, 0,
                              daoconst.CHIP_TYPE_CHIP)
        bireport.reportBiChip(userId, coin, coin, coin,
                              'DATA_FROM_MYSQL_2_REDIS_COIN',
                              intClientId, appId, appId, 0,
                              daoconst.CHIP_TYPE_COIN)
        bireport.reportBiChip(userId, diamond, diamond, diamond,
                              'DATA_FROM_MYSQL_2_REDIS_DIAMOND',
                              intClientId, appId, appId, 0,
                              daoconst.CHIP_TYPE_DIAMOND)
        bireport.reportBiChip(userId, coupon, coupon, coupon,
                              'DATA_FROM_MYSQL_2_REDIS_COUPON',
                              intClientId, appId, appId, 0,
                              daoconst.CHIP_TYPE_COUPON)
        return 1
    return 0
Exemplo n.º 39
0
def _requestSdkUrl(url, params, needresponse=False):
    params['code'] = _sign(params)
    jsonstr, _ = webpage.webget(url, postdata_=params, needresponse=needresponse)
    if needresponse:
        try:
            data = strutil.loads(jsonstr)
            return data['result']
        except:
            ftlog.error()
            return BAD_RESPONSE
    return None
Exemplo n.º 40
0
def webgetJson(httpurl, datas={}, appKey=None, timeout=3):
    '''
    调用远程HTTP接口, 并返回JSON结果
    '''
    response, httpurl = webget(httpurl, datas, appKey, timeout=timeout)
    datas = None
    try:
        datas = strutil.loads(response)
    except:
        ftlog.error(httpurl, 'response=', response)
    return datas, httpurl
Exemplo n.º 41
0
def decodeUserMatchInfo(gameId, userId, bigRoomId, jstr):
    d = strutil.loads(jstr)
    if d:
        ret = UserMatchInfo(gameId, userId, bigRoomId)
        ret.state = d['st']
        ret.instId = d['instId']
        ret.ctrlRoomId = d['crid']
        fee = d.get('fee')
        if fee:
            ret.feeItem = TYContentItem.decodeFromDict(fee)
        return ret
    return None
Exemplo n.º 42
0
    def __init__(self, gameId):
        super(DiFangRobotManager, self).__init__()
        res = loadResource('robot_info.json')
        rinfo = strutil.loads(res)
        baseSnsId = rinfo['basesnsid'] + gdata.serverId()
        users = []
        names = ["rb_" + str(gameId) + "_" + str(uid) for uid in xrange(MAX_ROBOT_UID)]
        # names = ["rb_" + str(uid + 1) for uid in xrange(MAX_ROBOT_UID)]
        #         names = rinfo["names"]
        for x in xrange(len(names)):
            name = names[x]
            snsId = baseSnsId + '_' + str(gameId) + "_" + str(x)
            users.append(gdata.games()[gameId].RobotUserClass(None, snsId, name))
        self.freeRobotUsers = users

        ftlog.info('>> |gameId, robot user count:', gameId, len(users), caller=self)
Exemplo n.º 43
0
    def getConfigForClient(self, gameId, userId, clientId):
        client = copy.deepcopy(self._clientConf)
        shareid = self._serverConf['share']
        share = hallshare.findShare(shareid)
        if share:
            winrate = gamedata.getGameAttr(userId, 6, 'winrate')
            winrate = strutil.loads(winrate, ignoreException=True, execptionValue={})
            todotask = share.buildTodotask(HALL_GAMEID, userId, 'share_click',
                                           {'userId': userId, 'actName': client['id'],
                                            'dizhuPlayNum': winrate.get('pt', 0)})
            client['config']["share"] = todotask.toDict()

        actkey = ACTIVITY_KEY.format(HALL_GAMEID, userId, client['id'])
        total = daobase.executeUserCmd(userId, 'HGET', actkey, self.FIELD_TOTAL_CNT)
        client['config']['total'] = total if total else 0
        client['config']['today'] = self._get_click_cnt(userId, actkey)[1]
        return client
Exemplo n.º 44
0
def _getTcTemplatesByModuleKey(moduleKey, funDecode):
    # 取得redis中的所有原始数据
    xkey = 'game:' + moduleKey + ':' + CLIENT_ID_TEMPLATE
    datas = ftcon.getConfNoCache('GET', xkey)
    if datas:
        datas = strutil.loads(datas)
        datas = strutil.replaceObjRefValue(datas)
    else:
        datas = {'templates': {}}
    if funDecode:
        cachedata = funDecode(moduleKey, datas)
        assert (isinstance(cachedata, dict)), 'the cache templates data must be a dict !' + str(
            moduleKey) + ' funDecode=' + str(funDecode)
    else:
        cachedata = datas['templates']
    _templatesCache[moduleKey] = cachedata

    return cachedata
Exemplo n.º 45
0
    def _doLogin(self):
        loginur = gdata.httpSdkInner() + '/open/v3/user/processSnsId'
        params = {'svninfo': '$robot$',
                  'appId': str(self.gameId),
                  'ty_bindmobile': '',
                  'phoneType': '',
                  'imei': ['Xb6tiNAVcw5eLrd1F4JTW2dnDrGNr3P0EXl2x99NUeVYGHCQB6ECeQ=='],
                  'iccid': ['RcjQJPkcLGfazgYaKJGWd8hTMfWp8OVr86NEoHuo1C0fIaCKUsTAhuB7huInoqWf'],
                  'androidId': ['BwyJv/PH1UCPjZDob4BSPgiwpuTq4dYgt1OFMrAoLJTED4oxlxdnEtuXKiOJxpkV'],
                  'snsToken': '',
                  'mac': ['wn+rGmlh6/AG6S6O+7kew0ZaMHsfR0LstUtr/WOvXtX681nrM5c+406L0PvY3P7W'],
                  'ty_uid': '0',
                  'clientId': self.clientId,
                  'deviceName': self.name,
                  'snsId': strutil.tyDesEncode(self.snsId),
                  'deviceId': ''
                  }
        sigstr = ''
        pkeys = params.keys()
        pkeys.sort()
        for k in pkeys:
            sigstr = sigstr + str(k) + '=' + str(params[k]) + '&'
        sigstr = sigstr[:-1]
        code = strutil.md5digest(strutil.tyDesEncode(sigstr))
        params['code'] = code

        userInfo, _ = webpage.webget(loginur, params)
        userInfo = strutil.loads(userInfo, ignoreException=True, execptionValue=userInfo)
        if not isinstance(userInfo, dict):
            ftlog.warn('snsId=', self.snsId, 'login-> return error !', userInfo)
            self.stop()
            return
        if self.isbusy == 0:  # 已经关闭
            return

        ftlog.debug('snsId=', self.snsId, 'login->', userInfo)

        result = userInfo.get('result', {})
        self.userId = result.get('userId', 0)
        if not isinstance(self.userId, int) or self.userId < 0:
            raise Exception('robot user login false !' + self.snsId)
        ftlog.debug('Robot login ok snsId=', self.snsId, 'userId=', self.userId)
        self.userInfo = result
        self.checkState(CMD_LOGIN)
Exemplo n.º 46
0
def _parseRpcResult(mi, jstr, rpc):
    if jstr:
        try:
            modict = strutil.loads(jstr)
        except:
            ftlog.warn('RpcException msg=', mi)
            raise RpcException('RpcException ' + rpc + ' ! remote return format false, json=[' + repr(jstr) + ']')
    else:
        raise RpcException('RpcException ' + rpc + ' ! remote return is Empty !')

    if modict.get('ex', None):
        ftlog.warn('RpcException msg=', mi)
        raise RpcException('RpcException ' + rpc + ' ! remote Exception=' + modict.get('ex'))

    if modict.has_key('ret'):
        ret = modict['ret']
    else:
        ftlog.warn('RpcException msg=', mi)
        raise RpcException('RpcException ' + rpc + ' ! remote has no return !')
    return ret
Exemplo n.º 47
0
Arquivo: gm.py Projeto: zhaozw/hall37
    def _do_http_gm_playing_table_list(self, gameId, httpRequest, httpArgs, httpResult):
        '''获取某个房间正在玩的牌桌列表'''

        bigRoomId = int(httpArgs['bigRoomId'])
        ctrlRoomIds = gdata.bigRoomidsMap()[bigRoomId]
        playingTableList = []

        for ctrlRoomId in ctrlRoomIds:
            roomDef = gdata.roomIdDefineMap()[ctrlRoomId]
            for shadowRoomId in roomDef.shadowRoomIds:
                msg = utils.updateMsg(cmd='table', params={
                    'action': 'gm',
                    'sa': 'playingTableList',
                    'gameId': gameId,
                    'roomId': shadowRoomId,
                    'tableId': shadowRoomId * 10000 + 1,
                })
                ret = router.queryTableServer(msg, shadowRoomId)
                ftlog.debug('_do_http_gm_playing_table_list| shadowRoomId, ret:', shadowRoomId, ret)
                playingTableList += strutil.loads(ret)['result']['playingTableList']
        httpResult['playingTableList'] = playingTableList
Exemplo n.º 48
0
def _getFriendGameInfo(userId, gameIds, for_level_info, for_winchip, for_online_info=1):
    uid = int(userId)
    datas = {}
    gid, rid, tid, sid = 0, 0, 0, 0
    state = daoconst.OFFLINE
    if for_online_info:
        loclist = onlinedata.getOnlineLocList(uid)
        state = onlinedata.getOnlineState(uid)
        if len(loclist) > 0:
            _rid, _tid, _sid = loclist[0]
            # gid表示用户在哪个游戏中
            gid = strutil.getGameIdFromInstanceRoomId(_rid)
            # 检查是否可加入游戏
            if TYGame(gid).canJoinGame(userId, _rid, _tid, _sid):
                # rid/tid/sid表示用户所在的游戏是否可加入游戏
                # 分享出来的都是可以加入游戏的牌桌信息
                rid = _rid
                tid = _tid
                sid = _sid
            if ftlog.is_debug():
                ftlog.debug('getFriendGameInfo userId:', userId, ' gameId:', gid, ' roomId:', _rid, ' tableId:', _tid,
                            ' seatId:', _sid, ' can not join game....')
        if state == daoconst.OFFLINE:
            offline_time = gamedata.getGameAttr(uid, HALL_GAMEID, 'offlineTime')
            if not offline_time:  # 取不到离线时间,取上线时间
                offline_time = userdata.getAttr(uid, 'authorTime')
            if offline_time:
                offline_time = pktimestamp.parseTimeMs(offline_time)
                delta = datetime.now() - offline_time
                delta = delta.days * 24 * 60 + delta.seconds / 60  # 分钟数
            else:  # 异常情况
                delta = 24 * 60
            datas['offline_time'] = delta if delta > 0 else 1
        if rid > 0:
            try:
                room = gdata.roomIdDefineMap().get(rid, None)
                if room:
                    datas['room_name'] = room.configure['name']
            except:
                ftlog.error()
    # 构造回传给SDK的游戏数据
    datas.update({'uid': uid, 'gid': gid, 'rid': rid, 'tid': tid, 'sid': sid, 'state': state})

    if for_level_info:
        datas['level_game_id'] = 0
        datas['level'] = 0
        datas['level_pic'] = ''
        try:
            for gameId in gameIds:
                if gameId not in gdata.games():
                    continue
                dashifen_info = gdata.games()[gameId].getDaShiFen(uid, '')
                if dashifen_info:
                    level = dashifen_info['level']
                    if level > 0 and level > datas['level']:
                        datas['level_game_id'] = gameId
                        datas['level'] = level
                        level_pic = dashifen_info.get('picbig')
                        datas['level_pic'] = level_pic if level_pic else dashifen_info.get('pic')
        except:
            ftlog.error()

    if for_winchip:
        datas['winchip'] = 0
        datas['winchips'] = 0
        try:
            for gameId in gameIds:
                winchips, todaychips = gamedata.getGameAttrs(userId, gameId, ['winchips', 'todaychips'], False)
                winchips = strutil.parseInts(winchips)
                yest_winchip = 0
                todaychips = strutil.loads(todaychips, ignoreException=True)
                if todaychips and 'today' in todaychips and 'chips' in todaychips and 'last' in todaychips:
                    if pktimestamp.formatTimeDayInt() == todaychips['today']:
                        yest_winchip = todaychips['last']
                    elif pktimestamp.formatTimeYesterDayInt() == todaychips['today']:
                        yest_winchip = todaychips['chips']
                datas['winchip'] += yest_winchip
                datas['winchips'] += winchips
        except:
            ftlog.error()
    return datas
Exemplo n.º 49
0
    def doSdkSnsCallback(self):
        paramsDict = runhttp.getDict()
        # ftlog.debug("doGetGameInfoForSdk:", paramsDict)
        sdk_result = paramsDict.get('sdk_result')
        tcp_params = paramsDict.get('tcp_params')

        # from urllib import unquote
        # ftlog.debug("tcp_params:", tcp_params)
        try:
            tcp_params = json.loads(tcp_params)
        except:
            tcp_params = None

        if not tcp_params or not sdk_result:
            return ''

        from poker.util import strutil
        try:
            sdk_result = strutil.loads(sdk_result)
            sdk_result = sdk_result['result']
        except:
            ftlog.error()
            return ''

        action = tcp_params['action']

        userId = tcp_params.get('userId')
        gameId = tcp_params.get('gameId')
        clientId = tcp_params.get('clientId')

        ftlog.debug('sdk_result', sdk_result)

        # if sdk_result is None or 'ec' in sdk_result:
        #     return False, -1, u'请求失败'

        mo = MsgPack()
        mo.setCmd('friend_call')
        mo._ht['result'] = tcp_params
        # mo.setResult('action', 'query')
        for k in sdk_result:
            mo.setResult(k, sdk_result[k])

        userdata.clearUserCache(userId)

        try:
            if action == 'praise_friend':
                self.on_praise_friend(gameId, userId, clientId, mo)
            elif action == 'ready_invite_friend':
                self.on_ready_invite_friend(gameId, userId, clientId, mo)
                code = mo.getResult('code', 0)
                if code > 0:
                    return ''
            elif action == 'add_friend':
                self.on_add_friend(gameId, userId, clientId, mo)
            elif action == 'accept_friend':
                self.on_accept_friend(gameId, userId, clientId, mo)
            elif action == 'get_friends_rank':
                self.on_get_friends_rank(gameId, mo)
            elif action == 'get_friend_list':
                self.on_get_friend_list(userId, mo)
        except:
            import traceback
            traceback.print_exc()
        router.sendToUser(mo, userId)
        return ''
Exemplo n.º 50
0
def loadUserQuizStatus(gameId, userId, actId):
    jstr = daobase.executeUserCmd(userId, 'hget', 'act:%s:%s' % (gameId, userId), actId)
    if jstr:
        d = strutil.loads(jstr)
        return UserQuizStatus(userId).fromDict(d)
    return None
Exemplo n.º 51
0
def __loadRoomDefines(gdatas):
    '''
    需要整理一个全局的 serverid-roomid-roombaseinfo的大集合
    取得server_rooms.json的配置内容, key为服务ID, value为房间配置内容
    '''
    if _DEBUG:
        debug('loadRoomDefines begin')
    # 首先整理进程ID, 展开多房间进程的进程ID
    srvid_rooms_map = {}
    srvidmap = {}
    allserver = gdata.allServersMap()
    for k in allserver:
        srvid_rooms_map[k] = []
        if k.find('-') > 0:
            assert (k.find(gdata.SRV_TYPE_ROOM) == 0 or k.find(gdata.SRV_TYPE_TABLE) == 0)
            tail = '000'
            if k.find(gdata.SRV_TYPE_TABLE) == 0:
                tail = '001'
            ks = k.split('-')
            ps = int(ks[1])
            pe = int(ks[2])
            assert (ps > 0 and ps < 999)
            assert (pe > 0 and pe < 999)
            assert (ps < pe)
            for x in xrange(ps, pe + 1):
                playid = '%03d' % (x)
                sid = ks[0] + playid + ks[3]
                srvidmap[sid + tail] = k
        else:
            if k.find(gdata.SRV_TYPE_ROOM) == 0:
                srvidmap[k + '000'] = k
            if k.find(gdata.SRV_TYPE_TABLE) == 0:
                srvidmap[k] = k

    clsRoomDefine = namedtuple('RoomDefine', ['bigRoomId', 'parentId', 'roomId', 'gameId',
                                              'configId', 'controlId', 'shadowId', 'serverId',
                                              'tableCount', 'shadowRoomIds', 'configure'])
    roomid_define_map = {}
    big_roomids_map = {}
    gameid_big_roomids_map = {}
    # 取得说有挂接的游戏ID, 取得对应GAMEID的房间配置
    gameids = gdata.games().keys()
    if _DEBUG:
        debug('the game ids=', gameids)
    for gid in gameids:
        gameid_big_roomids_map[gid] = []
        roomdict = ftcon.getConfNoCache('GET', 'game:' + str(gid) + ':room:0')
        if roomdict:
            roomdict = strutil.loads(roomdict)
        if not isinstance(roomdict, dict):
            if _DEBUG:
                debug('the game of', gid, 'have no room !')
            continue
        for roomIdStr, configure in roomdict.items():
            bigRoomId = int(roomIdStr)
            gameid, configid = strutil.parseBigRoomId(bigRoomId)

            configure = __auto_change_room_count(configure)
            controlServerCount = int(configure['controlServerCount'])
            controlTableCount = int(configure['controlTableCount'])
            gameServerCount = int(configure['gameServerCount'])
            gameTableCount = int(configure['gameTableCount'])

            assert (gameid == gid)
            assert (configid > 0 and configid < 999), '%s,%s' % (roomIdStr, str(configure))
            assert (controlServerCount > 0 and controlServerCount < 9), '%s,%s' % (roomIdStr, str(configure))
            assert (controlTableCount >= 0 and controlTableCount < 9999), '%s,%s' % (roomIdStr, str(configure))
            assert (gameServerCount >= 0 and gameServerCount < 999), '%s,%s' % (roomIdStr, str(configure))
            assert (gameTableCount > 0 and gameTableCount < 9999), '%s,%s' % (roomIdStr, str(configure))
            assert (not bigRoomId in big_roomids_map)

            extconfig = ftcon.getConfNoCache('GET', 'game:' + str(gid) + ':room:' + str(bigRoomId))
            if extconfig:
                extconfig = strutil.loads(extconfig)
            if isinstance(extconfig, dict):
                configure.update(extconfig)

            gameid_big_roomids_map[gid].append(bigRoomId)
            big_roomids_map[bigRoomId] = []
            for m in xrange(controlServerCount):
                # 自动计算controlId, 重1开始
                controlId = m + 1
                controlRoomId = (bigRoomId * 10 + controlId) * 1000
                shadowRooms = []
                assert (not controlRoomId in big_roomids_map)
                assert (not controlRoomId in roomid_define_map)
                for n in xrange(gameServerCount):
                    # 自动计算shadowId, 重1开始, 此处为桌子运行的房间
                    shadowId = n + 1
                    shadowRoomId = controlRoomId + shadowId
                    assert (not shadowRoomId in roomid_define_map)
                    processId = gdata.SRV_TYPE_TABLE + str(shadowRoomId)
                    serverId = srvidmap[processId]
                    srvid_rooms_map[serverId].append(shadowRoomId)
                    shadowRooms.append(shadowRoomId)
                    roomid_define_map[shadowRoomId] = clsRoomDefine(bigRoomId, controlRoomId, shadowRoomId, gameid,
                                                                    configid, controlId, shadowId, serverId,
                                                                    gameTableCount, tuple([]), configure)
                    if _DEBUG:
                        debug('load room define->bigRoomId=', bigRoomId, 'parentId=', controlRoomId,
                              'roomId=', shadowRoomId, 'gameId=', gameid, 'configId=', configid,
                              'controlId=', controlId, 'shadowId=', shadowId, 'tableCount=', gameTableCount,
                              'serverId=', serverId)

                # 此处为控制房间
                processId = gdata.SRV_TYPE_ROOM + str(controlRoomId)
                serverId = srvidmap[processId]
                srvid_rooms_map[serverId].append(controlRoomId)
                big_roomids_map[bigRoomId].append(controlRoomId)
                roomid_define_map[controlRoomId] = clsRoomDefine(bigRoomId, 0, controlRoomId, gameid,
                                                                 configid, controlId, 0, serverId,
                                                                 controlTableCount, tuple(shadowRooms), configure)
                if _DEBUG:
                    debug('load room define->bigRoomId=', bigRoomId, 'parentId=', 0,
                          'roomId=', controlRoomId, 'gameId=', gameid, 'configId=', configid,
                          'controlId=', controlId, 'shadowId=', 0, 'tableCount=', controlTableCount,
                          'serverId=', serverId, 'shadowRooms=', shadowRooms)
        gameid_big_roomids_map[gid].sort()

    # 整理打印配置的内容
    if _DEBUG:
        debug('find big roomids=', big_roomids_map.keys())
    for k, v in big_roomids_map.items():
        if _DEBUG:
            debug('find big room id ', k, 'has childs :', v)
    for k in srvid_rooms_map.keys():
        if not srvid_rooms_map[k]:
            del srvid_rooms_map[k]
        else:
            if _DEBUG:
                debug('find server', k, 'has roomids :', srvid_rooms_map[k])

    gdatas['srvid_roomid_map'] = makeReadonly(srvid_rooms_map)
    gdatas['roomid_define_map'] = makeReadonly(roomid_define_map)
    gdatas['big_roomids_map'] = makeReadonly(big_roomids_map)
    gdatas['gameid_big_roomids_map'] = makeReadonly(gameid_big_roomids_map)
    if _DEBUG:
        debug('loadRoomDefines end')
Exemplo n.º 52
0
def _getWeakDataRedis(userId, dataKey):
    jsonstr = daobase.executeUserCmd(userId, 'GET', dataKey)
    data = strutil.loads(jsonstr, ignoreException=True, execptionValue={})
    if not isinstance(data, dict):
        data = {}
    return data
Exemplo n.º 53
0
def decodeRoomInfo(roomId, jstr):
    d = strutil.loads(jstr)
    return RoomInfo.fromDict(roomId, d)