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)
def _onUnExpectedUserLogin(event): userId = event.userId behaviourConf = dizhuconf.getUserBehaviourReward() if not _checkExpectedUser(userId, behaviourConf): if ftlog.is_debug(): ftlog.debug('_onUnExpectedUserLogin check failed userId=', userId) return _, intClientId = sessiondata.getClientIdNum(userId) expectedClientIds = behaviourConf.get('expectedClientIds', []) try: # 只处理配置中的clientId包的表外用户 if expectedClientIds and intClientId in expectedClientIds: todayDate = int(dizhu_util.calcTodayIssueNum()) olderInfo = daobase.executeUserCmd( event.userId, 'HGET', 'userBehaviour:6:' + str(userId), 'info') if olderInfo: olderInfo = strutil.loads(olderInfo) olderType = olderInfo.get('type', 0) olderDate = olderInfo.get('date', 0) if olderType in [ BEHAVIOUR_TYPE_REWARDED, BEHAVIOUR_TYPE_NOUSEED ]: # 已处理过的不再处理 return if olderDate - todayDate > 1: # 过期记录重新分组 behaviourInfo = { 'type': random.randrange(1, 4, 2), 'date': todayDate } daobase.executeUserCmd(userId, 'HSET', 'userBehaviour:6:' + str(userId), 'info', strutil.dumps(behaviourInfo)) ftlog.info('_onUnExpectedUserLogin userId=', userId, 'info=', behaviourInfo, 'olderInfo=', olderInfo) else: # 未记录过的表外用户平均分到1、3组 behaviourInfo = { 'type': random.randrange(1, 4, 2), 'date': todayDate } daobase.executeUserCmd(userId, 'HSET', 'userBehaviour:6:' + str(userId), 'info', strutil.dumps(behaviourInfo)) except Exception, e: ftlog.warn('_onUnExpectedUserLogin userId=', userId, 'error=', e)
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))
def saveFameHall(fameHall): d = fameHall.toDict() jstr = strutil.dumps(d) key = buildFameHallKey() daobase.executeRePlayCmd('hset', key, fameHall.rankId, jstr) if ftlog.is_debug(): ftlog.debug('saveFameHall rankId=', fameHall.rankId, 'jstr=', jstr)
def saveActivityScoreRankingInfo(rankingInfo): d = rankingInfo.toDict() jstr = strutil.dumps(d) key = buildActivityRankInfoKey() daobase.executeRePlayCmd('hset', key, rankingInfo.rankId, jstr) ftlog.info('saveActivityScoreRankingInfo rankId=', rankingInfo.rankId, 'jstr=', jstr)
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 startMatchTable(self, tableInfo): if ftlog.is_debug(): ftlog.debug('DizhuTableCtrlErdayiMatch.startMatchTable:', 'tableInfo=', strutil.dumps(tableInfo)) self._doClearMatchTable() self._updateMatchTableInfo(tableInfo) self._startMatchTable()
def saveUserMatchInfo(info): d = {'st': info.state, 'instId': info.instId, 'crid': info.ctrlRoomId} if info.feeItem: d['fee'] = info.feeItem.toDict() jstr = strutil.dumps(d) key = buildKey(info.gameId, info.userId) daobase.executeUserCmd(info.userId, 'hset', key, info.bigRoomId, jstr)
def addMatchNotify(gameId, userId, matchName, matchDesc, matchIcon, signinFee, timestamp, matchId, notifyType, gameType, matchIndex): '''notifyType[1正常2推荐]''' matchNotify = { 'gameId': gameId, 'gameType': gameType, 'matchIndex': matchIndex, 'userId': userId, 'matchName': matchName, 'matchDesc': matchDesc, 'matchIcon': matchIcon, 'signinFee': signinFee, 'timestamp': int(timestamp), 'notifyType': notifyType, 'uuid': uuid.uuid1().get_hex(), 'matchId': matchId } if ftlog.is_debug(): ftlog.debug('addMatchNotify', 'userId=', userId, 'matchNotify=', matchNotify) date = datetime.fromtimestamp(timestamp).strftime('%Y%m%d') daobase.executeRankCmd('HSET', notify_match_user_date_key % (userId, date), matchId, strutil.dumps(matchNotify)) daobase.executeRankCmd('SADD', notify_match_user_zset_key % userId, date) msg = MsgPack() msg.setCmd('hall') msg.setResult('action', 'addMatchNotify') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('matchNotify', matchNotify) router.sendToUser(msg, userId)
def setUserShareInfo(userId, weekDate, shareInfo): ret = daobase.executeUserCmd(userId, 'HSET', 'weekShareInfo:6:' + str(userId), weekDate, strutil.dumps(shareInfo)) if ftlog.is_debug(): ftlog.debug('setUserShareInfo userId=', userId, 'weekDate=', weekDate, 'shareInfo=', shareInfo, 'ret=', ret) # 新增数据时删除过期的周报数据 if ret: todayWeekDate = dizhu_util.calcWeekBeginIssueNum() shareFields = daobase.executeUserCmd(userId, 'HKEYS', 'weekShareInfo:6:' + str(userId)) for shareField in shareFields: if str(shareField).isdigit() and len(str(shareField)) == 8: diffTime = getTimeYMDStrDiff(shareField, todayWeekDate) #只保存本周和上周的 if diffTime > 7: daobase.executeUserCmd(userId, 'HDEL', 'weekShareInfo:6:' + str(userId), shareField) ftlog.info('setUserShareInfo delOldWeekData userId=', userId, 'weekDate=', shareField) return ret
def _triggerEnterTableEvent(self, event): tableId = event.tableId userId = event.userId if tableId in self._allTableDict: self._allPlayerDict[userId] = tableId self._allTableSeatDict[tableId].add(userId) if ftlog.is_debug(): ftlog.debug("_triggerEnterTableEvent", self._allPlayerDict) import time from poker.util import strutil from newfish.entity.task.task_system_user import RedState from newfish.entity.config import FISH_GAMEID from newfish.entity.redis_keys import GameData newbie7DayGiftData = gamedata.getGameAttrJson( userId, FISH_GAMEID, GameData.newbie7DayGiftData) # 新手7日礼包数据 if isinstance(newbie7DayGiftData, list) and len(newbie7DayGiftData) == 2: return redState = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.redState) # 新手任务状态 if redState < RedState.Complete: gamedata.setGameAttr( userId, FISH_GAMEID, GameData.newbie7DayGiftData, strutil.dumps( [util.getDayStartTimestamp(int(time.time())), []]))
def _changeUserBehaviourInfo(userId, ret, behaviourConf): try: reward = behaviourConf.get('reward') if behaviourConf else None if not reward: return ret['type'] = BEHAVIOUR_TYPE_REWARDED daobase.executeUserCmd(userId, 'HSET', 'userBehaviour:6:' + str(userId), 'info', strutil.dumps(ret)) mailStr = behaviourConf.get('mail', '幸运女神的眷顾使你获得了奖励') contentItems = TYContentItem.decodeList(reward) assetList = dizhu_util.sendRewardItems(userId, contentItems, mailStr, 'USER_BEHAVIOUR_REWARD', userId) datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, mailStr) # 发奖弹窗 rewardsList = [] for assetItemTuple in assetList: assetItem = assetItemTuple[0] reward = {} reward['name'] = assetItem.displayName reward['pic'] = assetItem.pic reward['count'] = assetItemTuple[1] rewardsList.append(reward) reward_task = TodoTaskShowRewards(rewardsList) TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, reward_task) ftlog.info('userBehaviour.sendReward userId=', userId, 'reward=', [(atp[0].kindId, atp[1]) for atp in assetList]) except Exception, e: ftlog.warn('_changeUserBehaviourInfo userId=', userId, 'ret=', ret, 'err=', e)
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 {}
def sendPrivate(cls, gameId, toUid, fromUid, text): """ 游戏记录(使用大厅的游戏记录功能) """ ct = timestamp.formatTimeSecond() msg = {"gameid": gameId, "time": ct, "text": text} if fromUid: msg["from"] = fromUid rediskey = message.REDIS_KEY.format(message.MESSAGE_TYPE_PRIVATE, message.HALL_GAMEID, toUid) msglist = message._msg_load_and_expire(toUid, rediskey) if len(msglist) >= 100: # 超100条删除 lastmsgval = None for msgval in msglist: if lastmsgval: if message._msg_order(lastmsgval) > message._msg_order( msgval): continue lastmsgval = msgval if lastmsgval: daobase.executeUserCmd(toUid, "HDEL", rediskey, lastmsgval["id"]) maxid = gamedata.incrGameAttr(toUid, message.HALL_GAMEID, "msg.id.max", 1) daobase.executeUserCmd(toUid, "HSET", rediskey, maxid, strutil.dumps(msg))
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
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, '保存失败')
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()
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]
def saveTreasureChest(self): ''' 持久化用户宝箱数据 ''' value = [t.toDict() for t in self.treasureChestList] if ftlog.is_debug(): ftlog.debug('UserTreasureChest.saveTreasureChest userId=', self.userId, 'value=', value) saveUserTreasureChest(self.userId, DIZHU_GAMEID, strutil.dumps(value))
def setNewbie7Day(userId): """ 设置新手八日礼包数据 """ ts = int(time.time()) gamedata.setGameAttr(userId, FISH_GAMEID, GameData.newbie7DayGiftData, strutil.dumps([util.getDayStartTimestamp(ts), []]))
def _onTableWinlose(event): status = gamedata.getGameAttrJson(event.userId, DIZHU_GAMEID, 'item.win.progress', {}) if ftlog.is_debug(): ftlog.debug('dizhuredenvelope._onTableWinlose userId=', event.userId, 'status=', status) if event.winlose.isWin: changed = False roomConf = gdata.getRoomConfigure(event.roomId) playMode = roomConf.get('playMode') for itemConf in _itemConfList: if not itemConf['playModes'] or playMode in itemConf['playModes']: changed = True itemId = str(itemConf['itemId']) winTimes = itemConf['winTimes'] progress = status.get(itemId, 0) + 1 status[itemId] = progress if progress >= winTimes: flagName = 'item.open.flag:%s' % (itemId) gamedata.setnxGameAttr(event.userId, HALL_GAMEID, flagName, 1) if changed: gamedata.setGameAttr(event.userId, DIZHU_GAMEID, 'item.win.progress', strutil.dumps(status)) if ftlog.is_debug(): ftlog.debug('dizhuredenvelope._onTableWinlose userId=', event.userId, 'status=', status, 'changed=', changed)
def saveUserMatchInfo(info): d = {"st": info.state, "instId": info.instId, "crid": info.ctrlRoomId} if info.feeItem: d["fee"] = info.feeItem.toDict() jstr = strutil.dumps(d) key = buildKey(info.gameId, info.userId) daobase.executeUserCmd(info.userId, "hset", key, info.bigRoomId, jstr)
def httpTodayCallback(httpObj): if httpObj: ftlog.info('hallsportlottery.httpTodayCallback', 'httpObj=', httpObj, 'httpContents=', httpObj.httpContents) global _sportlotteryMap for match in httpObj.httpContents: timestamp = match['timestamp'] if time.time() >= timestamp or time.time() + 7200 >= timestamp: continue date = datetime.datetime.fromtimestamp(timestamp).strftime( '%Y-%m-%d') daobase.executeMixCmd('hset', leagueDaykey % date, match['matchId'], strutil.dumps(match)) if int(match['matchId']) in _sportlotteryMap: continue try: sportObj = Sportlottery() sportObj.fromDict(match) sportObj.start() _sportlotteryMap[sportObj.matchId] = sportObj if ftlog.is_debug(): ftlog.debug('httpTodayCallback', 'sportObj=', sportObj) except: ftlog.warn('hallsportlottery.httpTodayCallback', 'match=', match) del httpObj
def saveMySkin(model): d = model.toDict() gamedata.setGameAttr(model.userId, DIZHU_GAMEID, 'table.skin', strutil.dumps(d)) if ftlog.is_debug(): ftlog.debug('saveMySkin userId=', model.userId, 'model=', model.toDict())
def saveVideoDataToCDN(userId, gameRound): videoId = '%s_%s' % (userId, gameRound.roundId) gameRoundDict = GameRoundCodecDictReplay().encode(gameRound) gameRoundDict['uid'] = userId uploadPath = 'dizhu/tupt/replay/videos/' + calcPath(videoId) if ftlog.is_debug(): ftlog.debug('obsystem.saveVideoDataToCDN userId=', userId, 'videoId=', videoId, 'path=', uploadPath, 'gameRoundDict=', gameRoundDict) upurl = None try: upurl = random.choice(_uploadUrls) ec, info = uploader.uploadVideo(upurl, _uploadToken, 'cdn37/' + uploadPath, strutil.dumps(gameRoundDict)) if ec == 0: return videoId raise TYBizException(ec, info) except TYBizException: raise except: ftlog.error('obsystem.saveVideoDataToCDN', 'userId=', userId, 'videoId=', videoId, 'url=', upurl, 'path=', uploadPath) raise TYBizException(-1, '保存失败')
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)
def saveUserInviteStatus(status): jstr = strutil.dumps(status.toDict()) daobase.executeUserCmd(status.userId, 'hset', 'invite:9999:%s' % (status.userId), 'status', jstr) if ftlog.is_debug(): ftlog.debug('hall_invite.saveUserInviteStatus', 'userId=', status.userId, 'jstr=', jstr)
def saveStatus(self, status): d = self._encodeStatus(status) jstr = strutil.dumps(d) if ftlog.is_debug(): ftlog.debug('QuweiTaskActivity.saveStatus', 'gameId=', self.gameId, 'actId=', self.actId, 'userId=', status.userId, 'jstr=', jstr) saveStatusData(self.gameId, status.userId, self.actId, jstr)
def updateHistoryClientIdsIfNeed(userId, gameId, numClientId): clientIds = getHistoryClientIds(userId, gameId) if not clientIds or clientIds[-1] != numClientId: clientIds.append(numClientId) if len(clientIds) > 2: clientIds = clientIds[-2:] jstr = strutil.dumps(clientIds) gamedata.setGameAttr(userId, gameId, 'hisClientIds', jstr)
def saveMatchInfo(matchInfo): d = matchInfo.toDict() jstr = strutil.dumps(d) if ftlog.is_debug(): ftlog.debug('obsystem.saveMatchInfo', 'matchId=', matchInfo.matchId, 'jstr=', jstr) daobase.executeRePlayCmd('hset', 'tupt.match.info:6', matchInfo.matchId, jstr)
def _handlerRpcCommand(msg): ''' 处理接收到的一个远程RPC调用 ''' t1 = time() if performance.PERFORMANCE_NET: netkey = msg.getKey(performance.NET_KEY) if netkey: netkey.append(gdata.serverId()) netkey.append('DO') netkey.append(float('%0.4f' % t1)) try: rpc = msg.getKey('rpc') argl = msg.getKey('argl') argd = msg.getKey('argd') markParams = _runenv._rpc_methods.get(rpc, None) ret = _invokeMethodLocked(markParams, argl, argd) if markParams['syncCall']: if performance.PERFORMANCE_NET: netkey = msg.getKey(performance.NET_KEY) if not netkey: netkey = [] mo = strutil.dumps({'ret': ret, performance.NET_KEY: netkey}) else: mo = strutil.dumps({'ret': ret}) router.responseQurery(mo) except Exception, e: ftlog.error('_handlerRpcCommand msg=', msg) try: if router.isQuery(): targs = ftsvr.getTaskRunArg() if not targs.get('responsed'): if performance.PERFORMANCE_NET: netkey = msg.getKey(performance.NET_KEY) if not netkey: netkey = [] mo = strutil.dumps({'ex': '_handlerRpcCommand Exception : ' + str(e), performance.NET_KEY: netkey}) else: mo = strutil.dumps({'ex': '_handlerRpcCommand Exception : ' + str(e)}) router.responseQurery(mo) except: ftlog.error()
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
def saveUserMatchInfo(info): d = { 'st': info.state, 'instId': info.instId, 'crid': info.ctrlRoomId } if info.feeItem: d['fee'] = info.feeItem.toDict() jstr = strutil.dumps(d) key = buildKey(info.gameId, info.userId) daobase.executeUserCmd(info.userId, 'hset', key, info.bigRoomId, jstr)
def __stringifyResponse(isjsonp, content, content_type=''): """ 序列化响应的数据内容 """ if isinstance(content, (str, unicode)): pass elif isinstance(content, MsgPack): content = content.pack() elif isinstance(content, (list, tuple, dict)): content = strutil.dumps(content) elif isinstance(content, set): content = strutil.dumps(list(content)) elif isinstance(content, (int, float, bool)): content = str(content) else: content = repr(content) if 'utf-8' in content_type: content = content.encode('utf-8') if isjsonp: callback = getParamStr('callback', '').strip() if len(callback) > 0: content = '%s(%s);' % (callback, content) return content
def _bireport(arglist, argdict): jsondata = ['BIREPORT', 'test'] jsondata.extend(arglist) jsondata.append(argdict) msg = pkstrutil.dumps(jsondata) ftlog.info(msg)
def doTryNotifyRebuy(self, roomId, userId): msg = runcmd.getMsgPack() ftlog.debug('msg=', msg, caller=self) userId = msg.getParam("userId") ret = gdata.rooms()[roomId].doTryNotifyRebuy(userId) router.responseQurery(strutil.dumps({'ret': ret}))
# -*- coding=utf-8 -*- import freetime.util.log as ftlog from hall.servers.util import activity5_handler from poker.util import strutil # 测试 gameId = 6 userId = 10001 clientId = 'Android_3.71_tyOneKey,tyAccount,tyGuest.yisdkpay4.0-hall6.wandou.tu' datas = activity5_handler._doActivity5ActMsgList(6, 10001, clientId) ftlog.info('_doActivity5ActMsgList=', strutil.dumps(datas)) datas = activity5_handler._doActivity5CityMsgList(6, 10001, clientId) ftlog.info('_doActivity5CityMsgList=', strutil.dumps(datas)) datas = activity5_handler._doActivity5PrizeMsgList(6, 10001, clientId) ftlog.info('_doActivity5PrizeMsgList=', strutil.dumps(datas)) datas = activity5_handler._doActivity5ExchangeItemList(6, 10001, clientId) ftlog.info('_doActivity5ExchangeItemList=', strutil.dumps(datas))
def _onOrderDelivery(event): from hall.entity import hallitem nowDT = datetime.now() order = event.orderDeliveryResult.order if ((_conf.startDT and nowDT < _conf.startDT) or (_conf.endDT and nowDT >= _conf.endDT)): if ftlog.is_debug(): ftlog.debug('buy_send_gift._onOrderDelivery outofTime userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'nowDT=', nowDT.strftime('%Y-%m-%d %H:%M:%S'), 'startDT=', _conf.startDT.strftime('%Y-%m-%d %H:%M:%S'), 'endDT=', _conf.endDT.strftime('%Y-%m-%d %H:%M:%S')) return giftConf = _conf.findGiftConf(order.productId) if not giftConf: if ftlog.is_debug(): ftlog.debug('buy_send_gift._onOrderDelivery noGiftConf userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'orderClientId=', order.clientId) return hallGameId = strutil.getGameIdFromHallClientId(order.clientId) if hallGameId not in giftConf.gameIds: if ftlog.is_debug(): ftlog.debug('buy_send_gift._onOrderDelivery notInGameIds userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'giftConf=', giftConf.conf, 'orderClientId=', order.clientId, 'hallGameId=', hallGameId, 'gameIds=', giftConf.gameIds) return count = 0 if giftConf.maxCount >= 0: limitD = gamedata.getGameAttrJson(order.userId, hallGameId, 'act.buy_send_gift', {}) count = limitD.get(order.productId, 0) if count + 1 > giftConf.maxCount: ftlog.info('buy_send_gift._onOrderDelivery overLimit userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'giftConf=', giftConf.conf if giftConf else None, 'orderClientId=', order.clientId, 'count=', count, 'maxCount=', giftConf.maxCount) return count += 1 limitD[order.productId] = count gamedata.setGameAttr(order.userId, hallGameId, 'act.buy_send_gift', strutil.dumps(limitD)) assetList = None if giftConf.giftContent: userAssets = hallitem.itemSystem.loadUserAssets(order.userId) # def sendContent(self, gameId, content, count, ignoreUnknown, timestamp, eventId, intEventParam): assetList = userAssets.sendContent(hallGameId, giftConf.giftContent, 1, True, pktimestamp.getCurrentTimestamp(), 'ACTIVITY_REWARD', 10043) changedDataNames = TYAssetUtils.getChangeDataNames(assetList) if assetList else set() contentStr = TYAssetUtils.buildContentsString(assetList) if assetList else '' if giftConf.mail: mail = strutil.replaceParams(giftConf.mail, {'gotContent': contentStr, 'price': order.product.price}) message.send(hallGameId, message.MESSAGE_TYPE_SYSTEM, order.userId, mail) changedDataNames.add('message') if changedDataNames: datachangenotify.sendDataChangeNotify(HALL_GAMEID, order.userId, changedDataNames) ftlog.info('buy_send_gift._onOrderDelivery sendGift userId=', event.userId, 'orderId=', order.orderId, 'productId=', order.productId, 'giftConf=', giftConf.conf if giftConf else None, 'orderClientId=', order.clientId, 'count=', count, 'maxCount=', giftConf.maxCount, 'assetList=', [(a[0].kindId, a[1]) for a in assetList] if assetList else None)
def _invokeRpcMethod(markParams, argl, argd): ''' 进程内其它方法调用RPC方法的代理方法 ''' rpc = markParams['rpc'] rpcSrvType = markParams['rpcSrvType'] groupIndex = markParams['groupIndex'] future = markParams['future'] groupVal = 0 dstSid = None if rpcSrvType == RPC_FIRST_SERVERID: dstSid = argl[0] else: if groupIndex >= 0: groupVal = argl[groupIndex] if rpcSrvType == gdata.SRV_TYPE_UTIL: dstSid = _getRpcDstServerId(router._utilServer, groupVal) elif rpcSrvType == gdata.SRV_TYPE_ROOM: dstSid = getRpcDstRoomServerId(groupVal, 1) elif rpcSrvType == gdata.SRV_TYPE_TABLE: dstSid = getRpcDstRoomServerId(groupVal, 0) elif rpcSrvType == gdata.SRV_TYPE_CONN: dstSid = _getRpcDstServerId(router._connServer, groupVal) elif rpcSrvType == gdata.SRV_TYPE_HTTP: dstSid = _getRpcDstServerId(router._httpServer, groupVal) elif rpcSrvType == gdata.SRV_TYPE_ROBOT: dstSid = _getRpcDstServerId(router._robotServer, groupVal) elif rpcSrvType == gdata.SRV_TYPE_AGENT: dstSid = _getRpcDstServerId(router._agentServer, groupVal) elif rpcSrvType == gdata.SRV_TYPE_SDK_HTTP: dstSid = _getRpcDstServerId(router._sdkHttpServer, groupVal) elif rpcSrvType == gdata.SRV_TYPE_SDK_GATEWAY: dstSid = _getRpcDstServerId(router._gatewayHttpServer, groupVal) elif rpcSrvType == gdata.SRV_TYPE_CENTER: for dst, logics in gdata.centerServerLogics().items(): if groupVal in logics: dstSid = dst break if not dstSid: dstSid = router._centerServer.sids[0] if not dstSid: raise RpcException('RpcException ' + rpc + '! can not location the target server, rpcSrvType=' + str( rpcSrvType) + ' groupVal=' + str(groupVal)) rpcid = _getRpcId() if dstSid == gdata.serverId(): if markParams['syncCall']: if future: # TODO: Future RPC CALL 1 return _FutureResultLocal(markParams, argl, argd) else: ret = _invokeMethodLocked(markParams, argl, argd) return strutil.cloneData(ret) else: ftt = FTLoopTimer(0.01, 0, _invokeMethodLocked, markParams, argl, argd) ftt.start() return None mi = strutil.dumps({'cmd': _runenv._CMD_RPC_, 'rpc': rpc, 'argl': argl, 'argd': argd }) if markParams['syncCall']: if future: # TODO: Future RPC CALL 1 return _FutureResultRemote(rpc, dstSid, mi, rpcid, str(groupVal), _runenv._RPC_TIME_OUT) else: try: jstr = wrapper.query(dstSid, mi, rpcid, str(groupVal), _runenv._RPC_TIME_OUT) except FTMsgPackException, e: raise e except Exception, e: ftlog.warn('RpcException msg=', mi) raise RpcException('RpcException ' + rpc + ' ! query remote false, ' + str(e)) return _parseRpcResult(mi, jstr, rpc)
def saveRoomInfo(gameId, roomInfo): d = roomInfo.toDict() jstr = strutil.dumps(d) daobase.executeMixCmd('hset', buildKey(gameId), roomInfo.roomId, jstr)
def saveUserQuizStatus(gameId, actId, status): d = status.toDict() jstr = strutil.dumps(d) daobase.executeUserCmd(status.userId, 'hset', 'act:%s:%s' % (gameId, status.userId), actId, jstr)
def ppsCountConfigCmds(): global _CONFIG_CMDS_, _CONFIG_COUNT_, _CONFIG_COUNT_TIME_ ct = datetime.now() dt = ct - _CONFIG_COUNT_TIME_ dt = dt.seconds + dt.microseconds / 1000000.0 pps = '%0.2f' % (_CONFIG_COUNT_ / dt) ftlog.hinfo("CONFIG_PPS", pps, 'CMDCOUNT', _CONFIG_COUNT_, 'DT %0.2f' % (dt), 'CMDS', strutil.dumps(_CONFIG_CMDS_)) _CONFIG_COUNT_TIME_ = ct _CONFIG_CMDS_ = {} _CONFIG_COUNT_ = 0