def saveTableRecord(cls, tableRecordInfo, gameId): #add by taoxc ftlog.debug('createTableRecord.saveTableRecord tableRecordInfo:', tableRecordInfo, 'gameId:', gameId) #保存用户数据 for userId, playerRecordInfo in tableRecordInfo.items(): recordKey = cls._getTableRecordKey(gameId, userId) ftlog.debug('createTableRecord.saveTableRecord recordKey:', recordKey) #通过recordKey获取当前玩家的战绩记录数据,如果超过最大存储则进行删除处理(同时删除对应的内容) userRecordKeys = gamedata.getGameAttr(userId, gameId, recordKey) if not userRecordKeys: userRecordKeys = [] ftlog.debug('createTableRecord.saveTableRecord recordKey content is null') else: userRecordKeys = json.loads(userRecordKeys) ftlog.debug('createTableRecord.saveTableRecord recordKey content:', userRecordKeys) if len(userRecordKeys) >= cls._user_record_count: #删除最早的记录(附带删除内容) lastestKey = userRecordKeys.pop(0) daobase.executeRePlayCmd('DEL', lastestKey) ftlog.debug('createTableRecord.saveTableRecord recordKey len > ', cls._user_record_count, ' delete key:', lastestKey) recordContentKey = cls._getTableRecordContentKey(gameId, userId) userRecordKeys.append(recordContentKey) #保存KEY gamedata.setGameAttr(userId, gameId, recordKey, json.dumps(userRecordKeys)) #保存内容 daobase.executeRePlayCmd('SET', recordContentKey, json.dumps(playerRecordInfo)) ftlog.debug('createTableRecord.saveTableRecord save keys:', userRecordKeys, ' save content:', playerRecordInfo)
def getWorshipRank(cls): """ 获取排行榜 """ currentTimestamp = pktimestamp.getCurrentTimestamp() key = buildUserCostKey() first_updated_at = daobase.executeRePlayCmd('hget', key, 'first_updated_at') or currentTimestamp if pktimestamp.is_same_day(currentTimestamp, first_updated_at): ret = [] key = buildWorshipRankKey() datas = daobase.executeRePlayCmd('zrevrange', key, 0, -1, 'withscores') if datas: for i in xrange(len(datas) / 2): userId = int(datas[i * 2]) chip = int(datas[i * 2 + 1]) userName, purl = userdata.getAttrs(userId, ['name', 'purl']) ret.append({'nickname': str(userName), 'img': purl, 'userId': userId, 'chip': chip, 'rank': i+1}) return ret else: key = buildUserCostKey() clearUserCost() clearRankList() daobase.executeRePlayCmd('hset', key, 'first_updated_at', currentTimestamp) ftlog.info('WorshipHelper.getWorshipRank first_updated_at=', first_updated_at) return []
def saveToGameData(cls, userId, gameDataKey, replayKey, gameId): """ 往gamedata下添加数据 """ replayDBKey = 'replay:%s' % (gameId) ftlog.debug("MJCreateTableRecord_saveToGameData userId", userId , "gameDataKey", gameDataKey , "replayKey", replayKey , "replayDBKey", replayDBKey) if daobase.executeUserCmd(userId, 'HEXISTS', gameDataKey, 'game_record'): ftlog.debug("MJCreateTableRecord_saveToGameData1") recordData = daobase.executeUserCmd(userId, 'HGET', gameDataKey, 'game_record') ftlog.debug("MJCreateTableRecord_saveToGameData2,recordData type = ", type(recordData), "content =", recordData) recordList = json.loads(str(recordData)) ftlog.debug("MJCreateTableRecord_saveToGameData2,recordList type = ", type(recordList), "content =", recordList) if recordList and isinstance(recordList, dict): while len(recordList['recordIndex']) >= 20: wastedReplayKey = recordList['recordIndex'].pop(0) hasKey = daobase.executeRePlayCmd('HEXISTS', replayDBKey, wastedReplayKey) if hasKey: daobase.executeRePlayCmd('HDEL', replayDBKey, wastedReplayKey) recordList['recordIndex'].append(replayKey) ftlog.debug("MJCreateTableRecord_saveToGameData3") daobase.executeUserCmd(userId, 'HSET', gameDataKey, 'game_record', json.dumps(recordList)) else: recordData = {"recordIndex": []} recordData['recordIndex'].append(replayKey) daobase.executeUserCmd(userId, 'HSET', gameDataKey, 'game_record', json.dumps(recordData))
def getTotalUserRedEnvelope(issue, userId): """ 获取总用户红包 """ key = buildUserRedEnvelopeKey(issue) ret = daobase.executeRePlayCmd('hget', key, userId) if not ret: return 0 return daobase.executeRePlayCmd('hvals', )
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 onMatchingFinish(event): try: sequence = int(event.instId.split('.')[1]) key = buildMatchPromotionKey(event.matchId, sequence) datas = daobase.executeRePlayCmd('zrange', key, 0, -1, 'withscores') if not datas: ftlog.info('matchhistory onMatchingFinish', 'gameId=', event.gameId, 'matchId=', event.matchId, 'instId=', event.instId, 'does not support persist') return dateStr = datas[0] value = getMatchHistoryRankByDate(event.matchId, dateStr) if value: value.append(datas[2:]) else: value = [datas[2:]] saveMatchHistoryRank(event.matchId, dateStr, json.dumps(value)) daobase.executeRePlayCmd('del', key) except Exception, e: ftlog.error('matchhistory onMatchingFinish', 'gameId=', event.gameId, 'matchId=', event.matchId, 'instId=', event.instId, 'err=', e.message)
def saveMatchHistoryRank(matchId, dateStr, value): key = buildMatchHistoryRankKey(matchId) ftlog.info('matchhistory saveMatchHistoryRank', 'matchId=', matchId, 'key=', key, 'dateStr=', dateStr, 'value=', value) daobase.executeRePlayCmd('hset', key, dateStr, value)
def pushRecord(cls, record): ''' 增加一条抽奖记录 ''' daobase.executeRePlayCmd('lpush', buildRecordUniqueKey(), record) length = daobase.executeRePlayCmd('llen', buildRecordUniqueKey()) if length > _worshipConf.messageNumber: daobase.executeRePlayCmd('ltrim', buildRecordUniqueKey(), 0, _worshipConf.messageNumber - 1)
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 removeMatchings(matchId): if not _obSwitch: return ftlog.info('obsystem._removeMatchings matchId=', matchId) matchingId = daobase.executeRePlayCmd('rpop', 'tupt.match.expiresList:6:%s' % (matchId)) while matchingId: removeVideos(matchId, matchingId) matchingId = daobase.executeRePlayCmd('rpop', 'tupt.match.expiresList:6:%s' % (matchId))
def saveRankingInfo(rankingInfo): d = rankingInfo.toDict() jstr = strutil.dumps(d) key = buildRankInfoKey() daobase.executeRePlayCmd('hset', key, rankingInfo.rankId, jstr) if ftlog.is_debug(): ftlog.debug('saveRankingInfo rankId=', rankingInfo.rankId, 'jstr=', jstr)
def saveRollLoseStreak(issue, userId, loseStreak): """ 连输记录 """ try: key = buildUserLoseKey(issue) daobase.executeRePlayCmd('hset', key, userId, loseStreak) except Exception, e: ftlog.error('dizhu_red_envelope_bomb.saveRollLoseStreak', 'err=', e.message)
def _saveRecordInAllList(cls, budgets, replayKey, gameId): """存储新的record到所有record列表中 """ replayDBKey = 'replay:%s' % (gameId) hasKey = daobase.executeRePlayCmd('HEXISTS', replayDBKey, replayKey) if not hasKey: daobase.executeRePlayCmd('HSET', replayDBKey, replayKey, json.dumps(budgets))
def clearVideoPrizeSentFlagByIssueNumber(issueNumber, videoId): ''' 清除用户发送奖励的标记,在发送失败时调用,以便重发 ''' if ftlog.is_debug(): ftlog.debug('replay_ranking_prize_sender.clearVideoPrizeSentFlagByIssueNumber', 'videoId=', videoId, 'issueNumber=', issueNumber) daobase.executeRePlayCmd('HDEL', buildReplayRankingPrizeKey(issueNumber), videoId)
def saveMatchLotteryInfo(userId, fee): # 保存用户报名券报名信息 jstr = daobase.executeRePlayCmd('hget', 'match:discount:6:', userId) match_discount = strutil.loads(jstr) if jstr else [] match_discount.append(fee[0]) jstr = strutil.dumps(match_discount) daobase.executeRePlayCmd('hset', 'match:discount:6', userId, jstr) if ftlog.is_debug(): ftlog.debug('saveMatchLotteryInfo userId=', userId, 'fee=', fee, 'jstr=', jstr)
def updateRewardIdInfo(cls, nowTimestamp): ''' ID 从 1000001 开始 ''' timstamp = int( daobase.executeRePlayCmd('HGET', 'reward.id.number', 'timestamp') or 0) if not pktimestamp.is_same_day(nowTimestamp, timstamp): daobase.executeRePlayCmd('HSET', 'reward.id.number', 'number', 1000000) daobase.executeRePlayCmd('HSET', 'reward.id.number', 'timestamp', nowTimestamp)
def saveReplay(replay): daobase.executeRePlayCmd('hmset', 'tupt.replay:6:%s' % (replay.videoId), 'userId', replay.userId, 'roomId', replay.roomId, 'roomName', replay.roomName, 'stageName', replay.stageName, 'details', strutil.dumps(replay.details), 'ts', replay.timestamp) ftlog.info('obsystem.saveReplay', 'videoId=', replay.videoId)
def increaseUserPlayCount(issue, userId, bigRoomId, timestamp): """ 每天每个房间玩得局数 """ try: key = buildUserPlayCountKey(issue) ret = daobase.executeRePlayCmd('hget', key, userId) if ret: ret = json.loads(ret) if not pktimestamp.is_same_day(timestamp, ret.get('timestamp')): daobase.executeRePlayCmd('hdel', key, userId) daobase.executeRePlayCmd( 'hset', key, userId, json.dumps({ str(bigRoomId): 1, 'timestamp': timestamp })) else: ret.setdefault(str(bigRoomId), 0) ret[str(bigRoomId)] = ret[str(bigRoomId)] + 1 ret['timestamp'] = timestamp daobase.executeRePlayCmd('hset', key, userId, json.dumps(ret)) else: daobase.executeRePlayCmd( 'hset', key, userId, json.dumps({ str(bigRoomId): 1, 'timestamp': timestamp })) except Exception, e: ftlog.error('dizhu_red_envelope_bomb.increaseUserPlayCount', 'userId=', userId, 'err=', e.message)
def clearUserCost(): """清理用户花费""" try: key = buildUserCostKey() daobase.executeRePlayCmd('del', key) if ftlog.is_debug(): ftlog.debug('dizhuworship.clearUserCost', 'key=', key) except Exception, e: ftlog.error('dizhuworship.clearUserCost', 'err=', e.message)
def clearRankList(): """清理排行榜""" try: key = buildWorshipRankKey() daobase.executeRePlayCmd('del', key) if ftlog.is_debug(): ftlog.debug('dizhuworship.clearRankList', 'key=', key) except Exception, e: ftlog.error('dizhuworship.clearRankList', 'err=', e.message)
def removeTableMatchings(matchId): info = getReplayMatchs().get(matchId) confHistoryLen = info.get('historyLen', 3) if info else 3 matchingLen = daobase.executeRePlayCmd('llen', 'tupt.match.expiresList:6:%s' % (matchId)) if matchingLen > confHistoryLen: matchingId = daobase.executeRePlayCmd('rpop', 'tupt.match.expiresList:6:%s' % (matchId)) while matchingId: if ftlog.is_debug(): ftlog.debug('obsystem._removeTableMatchings', 'matchId=', matchId, 'matchingId=', matchingId, 'confHistoryLen=', confHistoryLen) removeVideos(matchId, matchingId) matchingId = daobase.executeRePlayCmd('rpop', 'tupt.match.expiresList:6:%s' % (matchId))
def _getActiveUserListByTimer(): try: gdssUrl = 'http://gdss.touch4.me/?act=wxCommonApi.getActiveUserList&appid=wx992c1fb532d3bff3' userListInfo, _ = webpage.webgetGdss(gdssUrl, {}) userListInfo = json.loads(userListInfo) retcode = userListInfo.get('code') data = userListInfo.get('data') if retcode == 1 and data: daobase.executeRePlayCmd('SET', ACTIVE_USER_LIST_KEY, data) if ftlog.is_debug(): ftlog.debug('wx_official._getActiveUserList', 'activeUserList=', data[:50], '......') except Exception, e: ftlog.error('wx_official._getActiveUserListByTimer err=', e.message)
def insertRankList(actId, issue, userId, shareCharm, rankLimit=500): ''' 插入排行榜 ''' assert (rankLimit > 0) try: key = buildRankListKey(actId, issue) if daobase.executeRePlayCmd('EXISTS', key): if ftlog.is_debug(): ftlog.debug('activity_wx_share_charm.insertRankList userId=', userId, 'actId=', actId, 'key=', key, 'exists=', 1) daobase.executeRePlayCmd('ZADD', key, shareCharm, userId) else: daobase.executeRePlayCmd('ZADD', key, shareCharm, userId) daobase.executeRePlayCmd('EXPIRE', key, 86400 * 30) if ftlog.is_debug(): ftlog.debug('activity_wx_share_charm.insertRankList userId=', userId, 'actId=', actId, 'key=', key, 'exists=', 0) removed = daobase.executeRePlayCmd('ZREMRANGEBYRANK', str(key), 0, -rankLimit - 1) if ftlog.is_debug(): ftlog.debug('activity_wx_share_charm.insertRankList', 'userId=', userId, 'issue=', issue, 'shareCharm=', shareCharm, 'rankLimit=', rankLimit, 'removed=', removed) except Exception, e: ftlog.error('activity_wx_share_charm.insertRankList', 'userId=', userId, 'issue=', issue, 'shareCharm=', shareCharm, 'rankLimit=', rankLimit, 'err=', e.message)
def insertRanklist(rankId, issueNum, userId, score, rankLimit): assert (rankLimit > 0) try: key = buildRanklistKey(rankId, issueNum) daobase.executeRePlayCmd('zadd', key, score, userId) removed = daobase.executeRePlayCmd('zremrangebyrank', str(key), 0, -rankLimit - 1) if ftlog.is_debug(): ftlog.debug('insertRanklist', 'rankId=', rankId, 'issueNum=', issueNum, 'userId=', userId, 'score=', score, 'rankLimit=', rankLimit, 'removed=', removed) except: ftlog.error('insertRanklist', 'rankId=', rankId, 'issueNum=', issueNum, 'userId=', userId, 'score=', score, 'rankLimit=', rankLimit)
def updateUserCost(cls, userId, cost): """更新用户花费""" # 每天一更新 currentTimestamp = pktimestamp.getCurrentTimestamp() key = buildUserCostKey() first_updated_at = daobase.executeRePlayCmd('hget', key, 'first_updated_at') or currentTimestamp if pktimestamp.is_same_day(currentTimestamp, first_updated_at): userCost = saveUserCost(userId, cost) insertRankList(userId, userCost) else: clearUserCost() clearRankList() key = buildUserCostKey() daobase.executeRePlayCmd('hset', key, 'first_updated_at', currentTimestamp) ftlog.info('WorshipHelper.updateUserCost first_updated_at=', first_updated_at)
def _initialize(): ftlog.info('dizhuworship._initialize begin') global _inited key = buildUserCostKey() first_updated_at = daobase.executeRePlayCmd('hget', key, 'first_updated_at') if not first_updated_at: first_updated_at = pktimestamp.getCurrentTimestamp() daobase.executeRePlayCmd('hset', key, 'first_updated_at', first_updated_at) if not _inited: _inited = True _reloadConf() pkeventbus.globalEventBus.subscribe(EventConfigure, _onConfChanged) ftlog.info('dizhuworship._initialize end, first_updated_at=', first_updated_at)
def saveUserFishingCount(userId, fishId, count): key = buildUserFishingCountKey(userId) ret = daobase.executeRePlayCmd('hset', key, fishId, count) if ftlog.is_debug(): ftlog.debug('saveUserFishingCount userId=', userId, 'fishId=', fishId, 'count=', ret) return int(ret) if ret else 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
def getActiveUserList(): ret = daobase.executeRePlayCmd('GET', ACTIVE_USER_LIST_KEY) if not ret: return [] if ftlog.is_debug(): ftlog.debug('wx_official.getActiveUserList', 'activeUserList=', ret) return ret
def _saveGameRound(matchId, matchingId, userId, stageName, gameRound): if ftlog.is_debug(): ftlog.debug('obsystem._saveGameRound', 'matchId=', matchId, 'matchingId=', matchingId, 'userId=', userId, 'stageName=', stageName, 'roundId=', gameRound.roundId) replay = saveVideo(userId, stageName, gameRound) daobase.executeRePlayCmd('lpush', 'tupt.replayList:6:%s' % (matchingId), replay.videoId) addReplayToRank(matchingId, replay) ftlog.info('obsystem._saveGameRound', 'matchId=', matchId, 'matchingId=', matchingId, 'userId=', userId, 'stageName=', stageName, 'videoId=', replay.videoId)
def _sendAllRecordToUser(cls , userId , gameId , startRecordIndex , endRecordIndex , playMode=None , targetUserId=None , targetTableNo=None ): """全量下发 带分页参数 """ #获取keys if targetUserId is None: targetUserId = userId recordKey = cls._getTableRecordKey(gameId, targetUserId) ftlog.debug('createTableRecord.sendAllRecordToUser2 recordKey:', recordKey, 'startRecordIndex:', startRecordIndex, 'endRecordIndex:', endRecordIndex) if startRecordIndex < 0: startRecordIndex = 0 if endRecordIndex < startRecordIndex: endRecordIndex = startRecordIndex userRecordKeys = gamedata.getGameAttr(targetUserId, gameId, recordKey) if not userRecordKeys: userRecordKeys = [] ftlog.debug('createTableRecord.sendAllRecordToUser2 recordKey content is null') else: userRecordKeys = json.loads(userRecordKeys) ftlog.debug('createTableRecord.sendAllRecordToUser2 recordKey content:', userRecordKeys) rLength = len(userRecordKeys) urKeys = [] for index in range(startRecordIndex, endRecordIndex + 1): newIndex = rLength - index - 1 if newIndex >= 0: urKeys.append(userRecordKeys[rLength - index - 1]) ftlog.debug('createTableRecord.sendAllRecordToUser2 urKeys:', urKeys) msg = MsgPack() msg.setCmd('create_table') msg.setResult('action', 'record') msg.setResult('type', 'update') playerRecordList = [] for userRecordKey in urKeys: playerRecordInfo = daobase.executeRePlayCmd('GET', userRecordKey) if not playerRecordInfo: ftlog.warn('createTableRecord.sendAllRecordToUser2 key:', userRecordKey, ' is null') else: playerRecordDist = json.loads(playerRecordInfo) # playMode过滤 if playMode and playMode != playerRecordDist.get('playMode'): continue # 房间号过滤 if targetTableNo and targetTableNo != playerRecordDist.get('tableNo'): continue playerRecordList.append(playerRecordDist) ftlog.debug('createTableRecord.sendAllRecordToUser2 key:', userRecordKey, ' content:', playerRecordDist) msg.setResult('list', playerRecordList) router.sendToUser(msg, userId)
def sendAllRecordToUser(cls, userId, gameId): """全量下发 """ gameDataKey = cls._getUserRecordKey(userId, gameId) replayDBKey = 'replay:%s' % (gameId) if daobase.executeUserCmd(userId, 'HEXISTS', gameDataKey, 'game_record'): gameRecord = daobase.executeUserCmd(userId, 'HGET', gameDataKey, 'game_record') ftlog.debug("sendAllRecordToUser.gameRecord = ", gameRecord) recordData = json.loads(gameRecord) if len(recordData['recordIndex']) > 0: records = [] for temp in recordData['recordIndex']: record = daobase.executeRePlayCmd('HGET', replayDBKey, temp) if record: records.append(record) ftlog.debug("sendAllRecordToUser.records = ", records) if isinstance(records, list) and len(records) > 0: msg = MsgPack() msg.setCmd('create_table') msg.setResult('action', 'record') msg.setResult('type', 'update') msg.setResult('gameId', gameId) retList = [] for recordStr in records: if not recordStr: continue try: ftlog.debug("sendAllRecordToUsersetRetData1") record = json.loads(recordStr) defaultScore = record.get('defaultScore', 0) urls = record.get('recordUrls', []) retData = {} retData['recordTime'] = record.get('time', 0) retData['createTableNo'] = record['tableNo'] # 客户端牌局回放key retData['tableRecordKey'] = '%s.%s' % ( record.get('createTime', 0), retData['createTableNo']) retData['record_download_info'] = [] retData['users'] = [] ftlog.debug("sendAllRecordToUsersetRetData2") for uid, info in record['budget'].items(): deltaScoreList = info.get('deltaScoreList', 0) score = info.get('score', []) if isinstance(score, int): score = [] retData['users'].append({'name': info['name'], 'score': score, 'userId': info['uid'], 'deltaScore': deltaScoreList}) # 胜负结果字段 if int(uid) == userId: if deltaScoreList > 0: retData['winScore'] = 1 elif deltaScoreList == 0: retData['winScore'] = 0 elif deltaScoreList < 0: retData['winScore'] = -1 else: retData['winScore'] = 0 if int(uid) == userId: retData['deltaScore'] = 0 - defaultScore for i in range(len(urls)): record_download_info_obj = {} record_download_info_obj['url'] = '%s' % (urls[i]) record_download_info_obj['fileType'] = '' record_download_info_obj['MD5'] = md5digest( record_download_info_obj['url']).upper() retData['record_download_info'].append(record_download_info_obj) ftlog.debug("sendAllRecordToUsersetRetData3", retData) retList.append(retData) except: ftlog.error('==sendAllRecordToUser ===', records, ' keys:', recordData['recordIndex']) msg.setResult('list', retList) router.sendToUser(msg, userId) else: return