def update(self, userId, gameId, clientId, activityId): ''' 未领取 + 有剩余 = 显示可领取 未领取 + 无剩余 = 显示倒计时 已领取 + xxx = 显示倒计时 {'isOK': True, 'nowTime': 1452161428.0, 'nextTime': 1452218400.0, 'hasGet': False, 'isRemain': True, 'tip': tip} ''' clientconf = self._clientConf serverconf = self._serverConf dataWrapper = self._dataWrapper timelist = Tool.dictGet(clientconf, "config.activate.timeList") startdate = serverconf.get("start") enddate = serverconf.get("end") #检测是否过期 if not self.checkOperative(): tip = Tool.dictGet(clientconf, "config.activate.outdateTip") return {"isOK": False, "tip": tip} #活动已经过期 nowstamp = Tool.datetimeToTimestamp(datetime.now()) rconf = {"isOK": True, "nowTime": nowstamp} # 上次领取的物品 itemconf = dataWrapper.getLastGetItem(userId) if itemconf: rconf.update({ "itemDesc": itemconf.get("itemDesc"), "itemCount": itemconf.get("count") }) arrive_timepoint = dataWrapper.getLastestTimePoint(timelist, startdate) next_timepoint = dataWrapper.getNextTimePoint(timelist, enddate) if next_timepoint: # 若存在下一个时间点 rconf["nextTime"] = Tool.datetimeToTimestamp(next_timepoint) count = 0 if arrive_timepoint: #已经达到至少一个领取时间点 has_get = dataWrapper.hasGet(userId, arrive_timepoint) # 是否已经领取 isvip = (UserInfo.getVipLevel(userId) > 0) if isvip: count = _redenvelopeWrapper.getCount() # 剩余红包数量 else: count = _redenvelopeWrapper.getGeneralCount() # 非VIP只检测普通红包数量 rconf.update({"hasGet": has_get, "isRemain": (count > 0)}) # 上次领取时间在昨天? today = datetime.now().replace(None, None, None, 0, 0, 0, 0) if arrive_timepoint < today: rconf.update({"isFirst": True}) else: #未达到领取时间 rconf.update({"hasGet": False, "isRemain": False, "isFirst": True}) ftlog.debug("TYActivityDdzRedEnvelope.update: userId", userId, "rconf=", rconf, "count=", count) return rconf
def update(self, userId, gameId, clientId, activityId, bankId): ''' 未领取 + 有剩余 = 显示可领取 未领取 + 无剩余 = 显示倒计时 已领取 + xxx = 显示倒计时 {'isOK': True, 'nowTime': 1452161428.0, 'nextTime': 1452218400.0, 'hasGet': False, 'isRemain': True, 'tip': tip} ''' clientconf = self._clientConf #检测是否过期 if not self.checkOperative(): tip = Tool.dictGet(clientconf, "config.activate.outdateTip") return {"isOK": False, "tip": tip} #活动已经过期 nowstamp = Tool.datetimeToTimestamp(datetime.now()) rconf = {"isOK": True, "nowTime": nowstamp} iteminfo = LuckyPacketHelper.getUserGetLastlyHistory(bankId, userId) if iteminfo: rconf.update({ "itemDesc": iteminfo.get("itemDesc"), "itemCount": iteminfo.get("count") }) timeservices = ConfigDatabase.getTimeServices(bankId) next_timepoint = timeservices.getFirstUnreachedDatetime() if next_timepoint: rconf["nextTime"] = Tool.datetimeToTimestamp(next_timepoint) arrive_timepoint = timeservices.getLastlyReachedDatetime() if arrive_timepoint: #已经达到至少一个领取时间点 current_issue = timeservices.getIssueNumber(arrive_timepoint) isget = LuckyPacketHelper.isUserGet(bankId, userId, current_issue) isvip = (UserInfo.getVipLevel(userId) > 0) if isvip: count = PacketRedisInterface.getAllPacketNumber( bankId, current_issue) # 剩余红包数量 else: count = PacketRedisInterface.getNormalPacketNumber( bankId, current_issue) # 非VIP只检测普通红包数量 rconf.update({"hasGet": isget, "isRemain": (count > 0)}) # 上次领取时间在昨天? today = datetime.now().replace(None, None, None, 0, 0, 0, 0) if arrive_timepoint < today: rconf.update({"isFirst": True}) else: #未达到领取时间 rconf.update({"hasGet": False, "isRemain": False, "isFirst": True}) ftlog.debug("LuckyPacket.update: userId=", userId, "bankId=", bankId, "rconf=", rconf, "count=", count) return rconf
def update(self, rank, isGroup): if isGroup == 0 and self.isGroup == 1: self.bestRank = int(rank) self.bestRankDate = int( Tool.datetimeToTimestamp(datetime.now())) self.isGroup = 0 elif isGroup == self.isGroup: if self.bestRank <= 0 or rank < self.bestRank: self.bestRank = int(rank) self.bestRankDate = int( Tool.datetimeToTimestamp(datetime.now())) if rank == 1 and self.isGroup == 0: self.crownCount += 1 self.playCount += 1
def getFirstUnreachedDatetime(self): ''' 获得未到达的最近的一个时间点,若今天没有时间点则返回明天第一个时间点(前提是明天的领取时间点在活动结束之前,否则返回False) :return datetime/False ''' res = None dnow = datetime.now() now = dnow.time() if dnow < self._datetime_start or dnow > self._datetime_end: return False for t in self._timelist: if now < t: res = t break if res: return datetime(dnow.year, dnow.month, dnow.day, res.hour, res.minute, res.second) first_time = self._timelist[0] datetime_today = datetime(dnow.year, dnow.month, dnow.day, first_time.hour, first_time.minute, first_time.second) timestamp_tomorrow = Tool.datetimeToTimestamp( datetime_today) + 24 * 60 * 60 datetime_tomorrow = datetime.fromtimestamp(timestamp_tomorrow) datetime_end = self._datetime_end if datetime_tomorrow <= datetime_end: return datetime_tomorrow return False
def getLastestTimePoint(cls, timelist, startdate): ''' 获得已经到达的最近的一个时间点,若未达到今天时间点则返回昨天最后的时间点(前提是昨天时间点在开始时间之后,否则返回False) :param timelist 时间列表 :param startdate 开始时间格式化字符串 :return datetime ''' l = [] for s in timelist: t = datetime.strptime(s, "%H:%M:%S").time() l.append(t) l.sort() res = None dnow = datetime.now() now = dnow.time() for t in l: if now >= t: res = t if res: return datetime(dnow.year, dnow.month, dnow.day, res.hour, res.minute, res.second) last_time = l[-1] datetime_today = datetime(dnow.year, dnow.month, dnow.day, last_time.hour, last_time.minute, last_time.second) timestamp_yesterday = Tool.datetimeToTimestamp( datetime_today) - 24 * 60 * 60 datetime_yesterday = datetime.fromtimestamp(timestamp_yesterday) datetime_start = datetime.strptime(startdate, '%Y-%m-%d %H:%M:%S') if datetime_yesterday >= datetime_start: return datetime_yesterday return False
def getNextTimePoint(cls, timelist, enddate): ''' 获得未到达的最近的一个时间点,若今天没有时间点则返回明天第一个时间点(前提是明天的领取时间点在活动结束之前,否则返回False) :param timelist 时间列表 :param enddate 活动结束时间的格式化字符串 :return datetime ''' l = [] for s in timelist: t = datetime.strptime(s, "%H:%M:%S").time() l.append(t) l.sort() res = None dnow = datetime.now() now = dnow.time() for t in l: if now < t: res = t break if res: return datetime(dnow.year, dnow.month, dnow.day, res.hour, res.minute, res.second) first_time = l[0] datetime_today = datetime(dnow.year, dnow.month, dnow.day, first_time.hour, first_time.minute, first_time.second) timestamp_tomorrow = Tool.datetimeToTimestamp( datetime_today) + 24 * 60 * 60 datetime_tomorrow = datetime.fromtimestamp(timestamp_tomorrow) datetime_end = datetime.strptime(enddate, '%Y-%m-%d %H:%M:%S') if datetime_tomorrow <= datetime_end: return datetime_tomorrow return False
def __init__(self): ## 许愿池配置列表的指向当前可以进行的index self.poolStepIndex = 0 ## 是否已经投入 self.isAlreadyPutted = False ## 计时 self.lastTimestamp = Tool.datetimeToTimestamp(datetime.now())
def getLastlyReachedDatetime(self): ''' 获得已经到达的最后的一个时间点,若未达到今天时间点则返回昨天最后的时间点(前提是昨天时间点在开始时间之后,否则返回False) 若活动已结束或者未开始,则返回False :return datetime/False ''' res = None dnow = datetime.now() tnow = dnow.time() if dnow < self._datetime_start or dnow > self._datetime_end: return False for t in self._timelist: if tnow >= t: res = t if res: return datetime(dnow.year, dnow.month, dnow.day, res.hour, res.minute, res.second) last_time = self._timelist[-1] datetime_today = datetime(dnow.year, dnow.month, dnow.day, last_time.hour, last_time.minute, last_time.second) timestamp_yesterday = Tool.datetimeToTimestamp( datetime_today) - 24 * 60 * 60 datetime_yesterday = datetime.fromtimestamp(timestamp_yesterday) datetime_start = self._datetime_start if datetime_yesterday >= datetime_start: return datetime_yesterday return False
def getCountingSeconds(cls, userId): ''' 获得计时的秒数 ''' data = Redis.readJson(userId, cls.countingTimerUniqueKey) laststamp = data.get('timestamp') if not laststamp: cls.resetCounting(userId) return -1 return Tool.datetimeToTimestamp(datetime.now()) - laststamp
def sendUserVipBenefits(userId, roomId, minRoomLevel, sendCount, chip): if minRoomLevel < 1 or sendCount <= 0: return False ## room level limit bigroomId = gdata.getBigRoomId(roomId) roomconf = gdata.getRoomConfigure(bigroomId) if not roomconf: return False roomlevel = roomconf.get('roomLevel', 1) if roomlevel < minRoomLevel: ftlog.debug('sendUserVipBenefits: roomlevel', 'userId=', userId, 'roomlevel=', roomlevel, 'minRoomLevel=', minRoomLevel) return False ## send number limit rediskey = 'vip.benefits' data = Redis.readJson(userId, rediskey) timestamp = data.get('timestamp', 0) counter = data.get('counter', 0) now = datetime.datetime.now() last = datetime.datetime.fromtimestamp(timestamp) if last.year != now.year or last.month != now.month or last.day != now.day: counter = 0 if counter >= sendCount: ftlog.debug('sendUserVipBenefits: sendCount', 'userId=', userId, 'sendCount=', sendCount, 'counter=', counter) return False data['counter'] = counter + 1 data['timestamp'] = Tool.datetimeToTimestamp(now) Redis.writeJson(userId, rediskey, data) UserInfo.incrChip(userId, 6, chip, 'BENEFITS_VIP_SEND') ftlog.debug('sendUserVipBenefits:', 'userId=', userId, 'counter=', data['counter'], 'chip=', chip) return True
def getTimePointListInRange(self, timelist, datetime_start, datetime_end): ''' 获得在指定时间范围内的时间点(datetime对象)列表 :param timelist: ["11:20:00", "17:30:00"] :param datetime_start: datetime对象,开始时间 :param datetime_end: datetime对象,结束时间 :return: [datetime, datetime, ...] ''' cursor = datetime(datetime_start.year, datetime_start.month, datetime_start.day, 0, 0, 0) # 生成在活动范围内的领取的时间点列表 r = [] while cursor <= datetime_end: for x in timelist: t = datetime.strptime(x, "%H:%M:%S").time() d = datetime(cursor.year, cursor.month, cursor.day, t.hour, t.minute, t.second) if d >= datetime_start and d <= datetime_end: r.append(d) cursor = datetime.fromtimestamp( Tool.datetimeToTimestamp(cursor) + 24 * 60 * 60) r.sort() return r
def onMatchOver(cls, userId, recordId, rank, iswin, rewards, isGroping, mixId=None, exchangeCode=None): ''' 比赛结束会被调用 :param userId: :param recordId: :param rank: :param iswin: :param rewards: :param isGroping: 是否是分组阶段 :param mixId: 混房Id :param exchangeCode: 红包兑换码 :return: ''' if userId < 10000: # robot return ftlog.debug('MatchHistoryHandler.onMatchOver: ', 'userId=', userId, 'recordId=', recordId, 'rank=', rank, 'isWin=', iswin, 'rewards=', rewards, 'isGroping=', isGroping, 'mixId=', mixId, 'exchangeCode=', exchangeCode) if not rewards: rewards = {} MatchHistoryDatabaseNew.addingHistoryEntry(userId, recordId, { 'time': Tool.datetimeToTimestamp(datetime.now()), 'rank': rank, 'reward': rewards.get('desc'), 'isGroping': isGroping, 'exchangeCode': exchangeCode }, mixId)
def notifyMatchOver(self, player, reason, rankRewards): ''' 通知用户比赛结束了 ''' try: exchangeMoney = rankRewards.conf.get('exchangeMoney', None) if rankRewards else None exchangeCode = None if exchangeMoney: exchangeCode = RedEnvelopeHelper.getRedEnvelopeCode( player.userId, self._room.gameId, exchangeMoney, self._room.roomId, self._room.match.matchId, player.rank) ftlog.info('MatchPlayerNotifierDizhu.notifyMatchOver matchId=', player.matchInst.matchId, 'instId=', player.matchInst.instId, 'userId=', player.userId, 'signinParams=', player.signinParams, 'stageIndex=', player.stage.index, 'rank=', player.rank, 'reason=', reason, 'rankRewards=', rankRewards, 'exchangeCode=', exchangeCode) lastBestRank = None record = MatchRecord.loadRecord(self._room.gameId, player.userId, self._room.match.matchId) if record: lastBestRank = record.bestRank # 获取房间名 roomName = player.matchInst.matchConf.getRoomName(player.mixId) arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(player.mixId) if player.mixId else self._room.bigRoomId, None) if arenaContent: roomName = arenaContent.get('showName') or roomName rewardId = None if (reason == MatchFinishReason.USER_WIN or reason == MatchFinishReason.USER_LOSER): try: if player.isQuit: rankRewards = None event_remote.publishMatchWinloseEvent( self._room.gameId, player.userId, self._room.match.matchId, reason == MatchFinishReason.USER_WIN, player.rank, player.matchInst.matchConf.stages[0].totalUserCount, rankRewards.conf if rankRewards else None) tempGameResult = 1 if reason == MatchFinishReason.USER_WIN else -1 hall51event.sendToHall51MatchOverEvent( player.userId, self._room.gameId, self._room.bigRoomId, tempGameResult, -1, -1) if rankRewards: from dizhu.entity.matchhistory import MatchHistoryHandler MatchHistoryHandler.onMatchOver( player.userId, player.matchInst.matchConf.recordId, player.rank, reason == MatchFinishReason.USER_WIN, rankRewards.conf if rankRewards else None, False, player.mixId, exchangeCode=exchangeCode) matchRewardSwitch = WxShareControlHelper.getMatchRewardSwitch( ) if matchRewardSwitch: from dizhu.game import TGDizhu rewardId = RewardAsyncHelper.genRewardId() rewards = [] for rewardInfo in rankRewards.rewards: rewards.append({ 'itemId': rewardInfo['itemId'], 'count': rewardInfo['count'] }) playerMixId = int( player.mixId) if player.mixId else None TGDizhu.getEventBus().publishEvent( UserRewardAsyncEvent( DIZHU_GAMEID, player.userId, REWARD_ASYNC_TYPE_AS_ARENA_MATCH, rewardId, rewards, matchId=playerMixId or player.matchInst.matchId, mixId=playerMixId or 0, rank=player.rank, sequence=int( player.matchInst.instId.split('.')[1]), roomName=roomName)) if not rankRewards: matchutil.report_bi_game_event( 'MATCH_REWARD', player.userId, player.matchInst.matchId, 0, int(player.matchInst.instId.split('.')[1]), 0, 0, 0, [ 0, 0, 0, player.rank, int(player.mixId) if player.mixId else 0, 0 ], 'match_reward') except: ftlog.error() # 比赛记录保存 try: event = { 'gameId': self._room.gameId, 'userId': player.userId, 'matchId': self._room.match.matchId, 'rank': player.rank, 'isGroup': 0, 'mixId': player.mixId } MatchRecord.updateAndSaveRecord(event) except: ftlog.error() msg = MsgPack() msg.setCmd('m_over') msg.setResult('rewardId', rewardId) msg.setResult('mixId', player.mixId) msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('userId', player.userId) msg.setResult('reason', reason) msg.setResult('rank', player.rank) msg.setResult('exchangeCode', exchangeCode) if rankRewards: msg.setResult('info', self.buildWinInfo(player, rankRewards)) else: msg.setResult('info', self.buildLoserInfo(player)) msg.setResult('mucount', player.matchInst.matchConf.stages[0].totalUserCount) msg.setResult('date', str(datetime.now().date().today())) msg.setResult('time', time.strftime('%H:%M', time.localtime(time.time()))) msg.setResult('addInfo', '') rewardDesc = '' if rankRewards: msg.setResult('reward', matchutil.buildRewards(rankRewards)) rewardDesc = matchutil.buildRewardsDesc(rankRewards) if rewardDesc: msg.setResult('rewardDesc', rewardDesc) msg.setResult('mname', roomName) clientId = sessiondata.getClientId(player.userId) # 微信分享 money = 0 if rankRewards: for r in rankRewards.rewards: if r['itemId'] == 'user:coupon': assetKind = hallitem.itemSystem.findAssetKind( 'user:coupon') displayRate = assetKind.displayRate money = round(r['count'] * 1.0 / displayRate, 2) kwargs = {'matchRank': {'money': money % 100, 'stop': player.rank}} shareInfo = commconf.getNewShareInfoByCondiction( self._room.gameId, clientId) msg.setResult( 'shareInfo', {'erweima': shareInfo['erweima'] if shareInfo else {}}) try: # 玩家红包记录 dizhushare.addMatchHistoryCount(self._room.bigRoomId, player.rank) userShareInfo = rankRewards.conf.get( 'shareInfo', {}) if rankRewards else {} rewardType, shareInfoNew = dizhushare.getArenaShareInfoNew( player.userId, player.matchInst.matchConf.feeRewardList, arenaContent, userShareInfo) if shareInfoNew: msg.setResult('shareInfoNew', shareInfoNew) # 设置奖状分享的todotask diplomaShare matchShareType = 'arena' if rewardType == 'redEnvelope' else 'group' shareTodoTask = commconf.getMatchShareInfo( player.userName, roomName, player.rank, rewardDesc, player.userId, matchShareType, clientId) if shareTodoTask: msg.setResult('shareTodoTask', shareTodoTask) if rankRewards: bigImg = rankRewards.conf.get('bigImg', '') if bigImg: msg.setResult('bidImg', bigImg) msg.setResult('beatDownUser', player.beatDownUserName) if rankRewards and rankRewards.todotask: msg.setResult('todotask', rankRewards.todotask) # 微信公众号消息 if player.rank == 1: from hall.game import TGHall msgParams = {'reward': rewardDesc, 'roomName': roomName} TGHall.getEventBus().publishEvent( OfficialMessageEvent(DIZHU_GAMEID, player.userId, RED_ENVELOPE, msgParams, mixId=player.mixId)) if ftlog.is_debug(): ftlog.debug( 'MatchPlayerNotifierDizhu.notifyMatchOver.redEnvelopeEvent userId=', player.userId, 'reward=', rewardDesc, 'rank=', player.rank, 'roomName=', roomName) # 冠军触发抽奖逻辑 match_lottery = MatchLottery() ret = match_lottery.checkMatchRank(player.userId, self._room.match.matchId, player.rank) if ret: msg.setResult('match_lottery', 1) # 局间奖励总数 if player.stageRewardTotal: msg.setResult('stageReward', {'count': player.stageRewardTotal}) if ftlog.is_debug(): ftlog.debug( 'MatchPlayerNotifierDizhu.notifyMatchOver userId=', player.userId, 'roomId=', self._room.roomId, 'rank=', player.rank, 'player=', player, 'stageRewardTotal=', player.stageRewardTotal) except Exception, e: ftlog.error('notifyMatchOver.getArenaShareInfoNew', 'userId=', player.userId, 'matchId=', self._room.match.matchId, 'err=', e.message) record = MatchRecord.loadRecord(self._room.gameId, player.userId, self._room.match.matchId) if record: msg.setResult( 'mrecord', { 'bestRank': record.bestRank, 'lastBestRank': lastBestRank, 'bestRankDate': record.bestRankDate, 'isGroup': record.isGroup, 'crownCount': record.crownCount, 'playCount': record.playCount }) else: from dizhu.activities.toolbox import Tool msg.setResult( 'mrecord', { 'bestRank': player.rank, 'lastBestRank': lastBestRank, 'bestRankDate': Tool.datetimeToTimestamp( datetime.now()), 'isGroup': 0, 'crownCount': 1 if player.rank == 1 else 0, 'playCount': 1 }) if not player.isQuit: router.sendToUser(msg, player.userId) # 混房冠军LED mixId = player.mixId if mixId: mixConf = MatchPlayerNotifierDizhu.getArenaMixConf( self._room.roomConf, mixId) if player.rank == 1 and mixConf.get('championLed'): arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(mixId) if mixId else self._room.roomId, clientId) if ftlog.is_debug(): ftlog.debug('MatchPlayerNotifierDizhu.notifyMatchOver', 'userId=', player.userId, 'roomId=', self._room.roomId, 'mixId=', mixId, 'roomName', mixConf.get('roomName'), 'rewardShow=', mixConf.get('rewardShow', rewardDesc), 'mixConf=', mixConf) # 冠军发送Led通知所有其他玩家 ledtext = dizhuled._mk_match_champion_rich_text( player.userName, arenaContent.get('name') if arenaContent else mixConf.get('roomName'), arenaContent.get('rewardShow') if arenaContent else mixConf.get('rewardShow', rewardDesc)) LedUtil.sendLed(ledtext, 'global') else: if player.rank == 1 and self._room.roomConf.get( 'championLed') and not player.isQuit: arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(mixId) if mixId else self._room.roomId, clientId) # 冠军发送Led通知所有其他玩家 ledtext = dizhuled._mk_match_champion_rich_text( player.userName, arenaContent.get('name') if arenaContent else roomName, arenaContent.get('rewardShow') if arenaContent else self._room.roomConf.get('rewardShow', rewardDesc)) LedUtil.sendLed(ledtext, 'global') sequence = int(player.matchInst.instId.split('.')[1]) matchutil.report_bi_game_event( 'MATCH_FINISH', player.userId, player.matchInst.matchId, 0, sequence, 0, 0, 0, [int(player.mixId) if player.mixId else 255], 'match_end')
def resetCounting(cls, userId): ''' 重置计时器到当前时间 ''' data = {'timestamp': Tool.datetimeToTimestamp(datetime.now())} Redis.writeJson(userId, cls.countingTimerUniqueKey, data)
def resetingCounterToCurrentTimestamp(self): ''' 重置计时器到当前时间戳 ''' self.lastTimestamp = Tool.datetimeToTimestamp(datetime.now())
def get(self, userId, gameId, clientId, activityId): ''' {'isOK': True, 'nowTime': 1452161428.0, 'nextTime': 1452218400.0, 'hasGet': False, 'isRemain': True, 'tip': tip} ''' clientconf = self._clientConf serverconf = self._serverConf dataWrapper = self._dataWrapper timelist = Tool.dictGet(clientconf, "config.activate.timeList") startdate = serverconf.get("start") enddate = serverconf.get("end") #检测是否过期 if not self.checkOperative(): tip = Tool.dictGet(clientconf, "config.activate.outdateTip") return {"isOK": False, "tip": tip} #活动已经过期 nowstamp = Tool.datetimeToTimestamp(datetime.now()) rconf = {"isOK": True, "nowTime": nowstamp} arrive_timepoint = dataWrapper.getLastestTimePoint(timelist, startdate) next_timepoint = dataWrapper.getNextTimePoint(timelist, enddate) if next_timepoint: # 若存在下一个时间点 rconf["nextTime"] = Tool.datetimeToTimestamp(next_timepoint) if not arrive_timepoint: #未达到领取时间 tip = Tool.dictGet(clientconf, "config.activate.cannotGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf has_get = dataWrapper.hasGet(userId, arrive_timepoint) # 是否已经领取 ftlog.debug("TYActivityDdzRedEnvelope.get: userId", userId, " has_get=", has_get) if has_get: # 已经领取了 tip = Tool.dictGet(clientconf, "config.activate.alreadyGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf isvip = (UserInfo.getVipLevel(userId) > 0) result = daobase.executeMixLua(_REDIS_LUA_GET_NAME, 2, isvip, random.randint(1, 10000000)) ftlog.debug("TYActivityDdzRedEnvelope.get: userId", userId, " result=", result, "isvip=", isvip) if not result: tip = Tool.dictGet(clientconf, "config.activate.emptyGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf # 领取红包的结果 result_count = result[1] # 领取红包项的配置 itemconf = _redenvelopeWrapper.getItemConfigWithPath(result[0]) result_name = str(itemconf.get('desc')) # 构造邮箱信息 assetsdict = {"assets": result_name, "count": str(result_count)} mail = Tool.dictGet(clientconf, "config.mail") mail = strutil.replaceParams(mail, assetsdict) # 发送奖励和邮箱信息 assets = {'itemId': itemconf.get("itemId"), 'count': result_count} UserBag.sendAssetsToUser(6, userId, assets, 'DDZ_ACT_REDENVELOPE', mail) # 发送LED的(条件满足) ok = self.sendLedIfNeed(userId, itemconf, result_count) ftlog.debug("TYActivityDdzRedEnvelope.get: sendLed-> userId=", userId, " ok=", ok) # 记录领取物品 assets.update({"itemDesc": itemconf.get('desc')}) dataWrapper.markGet(userId, arrive_timepoint, assets) # 日志记录领取 ftlog.debug("TYActivityDdzRedEnvelope:Get, ", "userId", userId, "gettime", str(datetime.now()), "assets", assets.get("itemId"), "count", assets.get("count"), "desc", assets.get("itemDesc"), "detail", assets) # 构造协议信息 itemtip = Tool.dictGet(clientconf, "config.activate.itemGetTip") itemtip = strutil.replaceParams(itemtip, assetsdict) rconf.update({ "isOK": True, "itemDesc": result_name, "itemCount": result_count, "tip": itemtip }) ftlog.debug("TYActivityDdzRedEnvelope.get: userId=", userId, " itemconf=", itemconf, "arrive_timepoint=", str(arrive_timepoint), "rconf=", rconf) return rconf
def getCountingSeconds(self): ''' 获得自resetCounterToCurrentTimestamp调用后到当前的时间(秒) ''' return Tool.datetimeToTimestamp(datetime.now()) - self.lastTimestamp
def notifyMatchOver(self, player, reason, rankRewards): ''' 通知用户比赛结束了 ''' try: ftlog.info('MatchPlayerNotifierDizhu.notifyMatchOver matchId=', player.matchInst.matchId, 'instId=', player.matchInst.instId, 'userId=', player.userId, 'stageIndex=', player.stage.index, 'rank=', player.rank, 'reason=', reason, 'rankRewards=', rankRewards) if (reason == MatchFinishReason.USER_WIN or reason == MatchFinishReason.USER_LOSER): try: event_remote.publishMatchWinloseEvent( self._room.gameId, player.userId, self._room.match.matchId, reason == MatchFinishReason.USER_WIN, player.rank, player.matchInst.matchConf.stages[0].totalUserCount, rankRewards.conf if rankRewards else None) from dizhu.entity.matchhistory import MatchHistoryHandler MatchHistoryHandler.onMatchOver( player.userId, player.matchInst.matchConf.recordId, player.rank, reason == MatchFinishReason.USER_WIN, rankRewards.conf if rankRewards else None, False) except: ftlog.error() # 比赛记录保存 try: event = { 'gameId': self._room.gameId, 'userId': player.userId, 'matchId': self._room.match.matchId, 'rank': player.rank, 'isGroup': 0 } MatchRecord.updateAndSaveRecord(event) except: ftlog.error() msg = MsgPack() msg.setCmd('m_over') msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('userId', player.userId) msg.setResult('reason', reason) msg.setResult('rank', player.rank) if rankRewards: msg.setResult('info', self.buildWinInfo(player, rankRewards)) else: msg.setResult('info', self.buildLoserInfo(player)) msg.setResult('mucount', player.matchInst.matchConf.stages[0].totalUserCount) msg.setResult('date', str(datetime.now().date().today())) msg.setResult('time', time.strftime('%H:%M', time.localtime(time.time()))) msg.setResult('addInfo', '') rewardDesc = '' if rankRewards: from dizhu.bigmatch.match import BigMatch msg.setResult('reward', BigMatch.buildRewards(rankRewards)) rewardDesc = BigMatch.buildRewardsDesc(rankRewards) if rewardDesc: msg.setResult('rewardDesc', rewardDesc) msg.setResult('mname', self._room.roomConf["name"]) try: msg.setResult('beatDownUser', player.beatDownUserName) if rankRewards and rankRewards.todotask: msg.setResult('todotask', rankRewards.todotask) # 设置奖状分享的todotask diplomaShare shareTodoTask = dizhudiplomashare.buildDiplomaShare( player.userName, self._room.roomConf["name"], player.rank, rewardDesc, player.userId) if shareTodoTask: msg.setResult('shareTodoTask', shareTodoTask) except: ftlog.debug('NobeatDownUser arena match') ftlog.exception() record = MatchRecord.loadRecord(self._room.gameId, player.userId, self._room.match.matchId) if record: msg.setResult( 'mrecord', { 'bestRank': record.bestRank, 'bestRankDate': record.bestRankDate, 'isGroup': record.isGroup, 'crownCount': record.crownCount, 'playCount': record.playCount }) else: from dizhu.activities.toolbox import Tool msg.setResult( 'mrecord', { 'bestRank': player.rank, 'bestRankDate': Tool.datetimeToTimestamp( datetime.now()), 'isGroup': 0, 'crownCount': 1 if player.rank == 1 else 0, 'playCount': 1 }) router.sendToUser(msg, player.userId) if player.rank == 1 and self._room.roomConf.get('championLed'): # 冠军发送Led通知所有其他玩家 ledtext = dizhuled._mk_match_champion_rich_text( player.userName, self._room.roomConf['name'], self._room.roomConf.get('rewardShow', rewardDesc)) LedUtil.sendLed(ledtext, 'global') sequence = int(player.matchInst.instId.split('.')[1]) self.report_bi_game_event('MATCH_FINISH', player.userId, player.matchInst.matchId, 0, sequence, 0, 0, 0, [], 'match_end') except: ftlog.error()
def get(self, userId, gameId, clientId, activityId, bankId): ''' {'isOK': True, 'nowTime': 1452161428.0, 'nextTime': 1452218400.0, 'hasGet': False, 'isRemain': True, 'tip': tip} ''' clientconf = self._clientConf #检测是否过期 if not self.checkOperative(): tip = Tool.dictGet(clientconf, "config.activate.outdateTip") return {"isOK": False, "tip": tip} #活动已经过期 nowstamp = Tool.datetimeToTimestamp(datetime.now()) rconf = {"isOK": True, "nowTime": nowstamp} timeservices = ConfigDatabase.getTimeServices(bankId) next_timepoint = timeservices.getFirstUnreachedDatetime() if next_timepoint: rconf["nextTime"] = Tool.datetimeToTimestamp(next_timepoint) arrive_timepoint = timeservices.getLastlyReachedDatetime() if not arrive_timepoint: #未达到领取时间 tip = Tool.dictGet(clientconf, "config.activate.cannotGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf current_issue = timeservices.getIssueNumber(arrive_timepoint) isget = LuckyPacketHelper.isUserGet(bankId, userId, current_issue) if isget: # 已经领取了 tip = Tool.dictGet(clientconf, "config.activate.alreadyGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf isvip = (UserInfo.getVipLevel(userId) > 0) iteminfo = LuckyPacketHelper.getPacket(bankId, current_issue, isvip) ftlog.debug("TYActivityDdzRedEnvelope.get: userId", userId, " iteminfo=", iteminfo, "isvip=", isvip) if not iteminfo: tip = Tool.dictGet(clientconf, "config.activate.emptyGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf itemId = iteminfo.get('itemId') itemCount = iteminfo.get('count', 0) itemDesc = self.getItemDesc(clientconf, iteminfo) iteminfo["itemDesc"] = itemDesc # 构造邮箱信息 assetsdict = {"assets": itemDesc, "count": str(itemCount)} mail = Tool.dictGet(clientconf, "config.mail") mail = strutil.replaceParams(mail, assetsdict) # 发送奖励和邮箱信息 assets = {'itemId': itemId, 'count': itemCount} UserBag.sendAssetsToUser(6, userId, assets, 'DDZ_ACT_REDENVELOPE', mail) # 发送LED的(条件满足) itemconf = self.getItemConf(clientconf, iteminfo) ok = self.sendLedIfNeed(userId, itemconf, itemCount) ftlog.debug("TYActivityDdzRedEnvelope.get: sendLed-> userId=", userId, " ok=", ok) # 记录领取物品 assets.update({"itemDesc": itemconf.get('desc')}) LuckyPacketHelper.setUserGet(bankId, userId, current_issue, iteminfo) # 日志记录领取 ftlog.debug("TYActivityDdzRedEnvelope:Get, ", "userId", userId, "gettime", str(datetime.now()), "assets", iteminfo.get("itemId"), "count", iteminfo.get("count"), "desc", iteminfo.get("itemDesc"), "detail", iteminfo) # 构造协议信息 itemtip = Tool.dictGet(clientconf, "config.activate.itemGetTip") itemtip = strutil.replaceParams(itemtip, assetsdict) rconf.update({ "isOK": True, "itemDesc": itemDesc, "itemCount": itemCount, "tip": itemtip }) ftlog.debug("LuckyPacket.get: userId=", userId, " itemconf=", itemconf, "arrive_timepoint=", str(arrive_timepoint), "rconf=", rconf) return rconf
def notifyMatchOver(self, player, reason, rankRewards): ''' 通知用户比赛结束了 ''' try: ftlog.info('MatchPlayerNotifierDizhu.notifyMatchOver matchId=', player.matchInst.matchId, 'instId=', player.matchInst.instId, 'userId=', player.userId, 'signinParams=', player.signinParams, 'stageIndex=', player.stage.index, 'rank=', player.rank, 'reason=', reason, 'rankRewards=', rankRewards) if (reason == MatchFinishReason.USER_WIN or reason == MatchFinishReason.USER_LOSER): try: if player.isQuit: rankRewards = None event_remote.publishMatchWinloseEvent( self._room.gameId, player.userId, self._room.match.matchId, reason == MatchFinishReason.USER_WIN, player.rank, player.matchInst.matchConf.stages[0].totalUserCount, rankRewards.conf if rankRewards else None) tempGameResult = 1 if reason == MatchFinishReason.USER_WIN else -1 hall51event.sendToHall51MatchOverEvent(player.userId, self._room.gameId, self._room.bigRoomId, tempGameResult, -1, -1) from dizhu.entity.matchhistory import MatchHistoryHandler MatchHistoryHandler.onMatchOver( player.userId, player.matchInst.matchConf.recordId, player.rank, reason == MatchFinishReason.USER_WIN, rankRewards.conf if rankRewards else None, False, player.mixId) if not rankRewards: matchutil.report_bi_game_event( 'MATCH_REWARD', player.userId, player.matchInst.matchId, 0, int(player.matchInst.instId.split('.')[1]), 0, 0, 0, [ 0, 0, 0, player.rank, int(player.mixId) if player.mixId else 0, 0 ], 'match_reward') except: ftlog.error() # 比赛记录保存 try: event = { 'gameId': self._room.gameId, 'userId': player.userId, 'matchId': self._room.match.matchId, 'rank': player.rank, 'isGroup': 0, 'mixId': player.mixId } MatchRecord.updateAndSaveRecord(event) except: ftlog.error() msg = MsgPack() msg.setCmd('m_over') msg.setResult('mixId', player.mixId) msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('userId', player.userId) msg.setResult('reason', reason) msg.setResult('rank', player.rank) if rankRewards: msg.setResult('info', self.buildWinInfo(player, rankRewards)) else: msg.setResult('info', self.buildLoserInfo(player)) msg.setResult('mucount', player.matchInst.matchConf.stages[0].totalUserCount) msg.setResult('date', str(datetime.now().date().today())) msg.setResult('time', time.strftime('%H:%M', time.localtime(time.time()))) msg.setResult('addInfo', '') rewardDesc = '' if rankRewards: msg.setResult('reward', matchutil.buildRewards(rankRewards)) rewardDesc = matchutil.buildRewardsDesc(rankRewards) if rewardDesc: msg.setResult('rewardDesc', rewardDesc) roomName = player.matchInst.matchConf.getRoomName(player.mixId) arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(player.mixId) if player.mixId else self._room.bigRoomId, None) if arenaContent: roomName = arenaContent.get('showName') or roomName msg.setResult('mname', roomName) shareInfo = matchutil.buildShareInfo( self._room.gameId, sessiondata.getClientId(player.userId)) msg.setResult('shareInfo', {'erweima': shareInfo['erweima'] if shareInfo else {}}) try: msg.setResult('beatDownUser', player.beatDownUserName) if rankRewards and rankRewards.todotask: msg.setResult('todotask', rankRewards.todotask) # 设置奖状分享的todotask diplomaShare shareTodoTask = dizhudiplomashare.buildDiplomaShare( player.userName, roomName, player.rank, rewardDesc, player.userId) if shareTodoTask: msg.setResult('shareTodoTask', shareTodoTask) if rankRewards: bigImg = rankRewards.conf.get('bigImg', '') if bigImg: msg.setResult('bidImg', bigImg) if ftlog.is_debug(): ftlog.debug( 'MatchPlayerNotifierDizhu.notifyMatchOver userId=', player.userId, 'roomId=', self._room.roomId, 'bigImg=', bigImg, 'rank=', player.rank, 'rankRewards.conf=', rankRewards.conf) except: ftlog.debug('NobeatDownUser arena match') ftlog.exception() # 冠军触发抽奖逻辑 try: from dizhu.games.matchutil import MatchLottery match_lottery = MatchLottery() ret = match_lottery.checkMatchRank(player.userId, self._room.match.matchId, player.rank) if ret: msg.setResult('match_lottery', 1) except: ftlog.debug('MatchLottery arena match') ftlog.exception() ########################### # 玩家红包记录 try: from dizhu.entity import dizhushare shareInfoConf = rankRewards.conf.get('shareInfo', {}) if rankRewards else {} rewardType = shareInfoConf.get('type', '') if shareInfoConf else '' shareNum, shareTotalNum = dizhushare.arenaMatchRewardRecord( player.userId, shareInfoConf) # 常规配置 championRewards = player.matchInst.matchConf.feeRewardList championShareInfo = championRewards[0].rankRewardsList[0].conf.get( 'shareInfo', {}) if arenaContent: # 分ip奖励配置 championRewards = arenaContent.get('rank.rewards', []) if championRewards and championRewards[0].get( 'ranking', {}).get('start', 0) == 1: championShareInfo = championRewards[0].get('shareInfo', {}) rmb = 0 matchShareType = 0 if championShareInfo and championShareInfo.get( 'type', '') == MATCH_REWARD_REDENVELOPE: # 冠军奖励金额 rmb = championShareInfo.get('rmb', 0) matchShareType = 1 if shareInfoConf and str(rewardType) == MATCH_REWARD_REDENVELOPE: rmb = shareInfoConf.get('rmb', 0) shareInfoNew = { "matchShareType": matchShareType, "shareNum": shareNum if shareNum else 0, "shareTotalNum": shareTotalNum if shareTotalNum else 0, "get": 1 if str(rewardType) == MATCH_REWARD_REDENVELOPE else 0, "rmb": '{0:.2f}'.format(rmb) } msg.setResult('shareInfoNew', shareInfoNew) except Exception, e: ftlog.error('MatchPlayerNotifierDizhu.notifyMatchOver', 'gameId=', self._room.gameId, 'userId=', player.userId, 'roomId=', self._room.roomId, 'matchId=', self._room.match.matchId, 'err=', e.message) ########################### record = MatchRecord.loadRecord(self._room.gameId, player.userId, self._room.match.matchId) if record: msg.setResult( 'mrecord', { 'bestRank': record.bestRank, 'bestRankDate': record.bestRankDate, 'isGroup': record.isGroup, 'crownCount': record.crownCount, 'playCount': record.playCount }) else: from dizhu.activities.toolbox import Tool msg.setResult( 'mrecord', { 'bestRank': player.rank, 'bestRankDate': Tool.datetimeToTimestamp(datetime.now()), 'isGroup': 0, 'crownCount': 1 if player.rank == 1 else 0, 'playCount': 1 }) if not player.isQuit: router.sendToUser(msg, player.userId) # 混房冠军LED mixId = player.mixId if mixId: mixConf = MatchPlayerNotifierDizhu.getArenaMixConf( self._room.roomConf, mixId) if player.rank == 1 and mixConf.get('championLed'): clientId = sessiondata.getClientId(player.userId) arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(mixId) if mixId else self._room.roomId, clientId) if ftlog.is_debug(): ftlog.debug('MatchPlayerNotifierDizhu.notifyMatchOver', 'userId=', player.userId, 'roomId=', self._room.roomId, 'mixId=', mixId, 'roomName', mixConf.get('roomName'), 'rewardShow=', mixConf.get('rewardShow', rewardDesc), 'mixConf=', mixConf) # 冠军发送Led通知所有其他玩家 ledtext = dizhuled._mk_match_champion_rich_text( player.userName, arenaContent.get('name') if arenaContent else mixConf.get('roomName'), arenaContent.get('rewardShow') if arenaContent else mixConf.get('rewardShow', rewardDesc)) LedUtil.sendLed(ledtext, 'global') else: if player.rank == 1 and self._room.roomConf.get( 'championLed') and not player.isQuit: clientId = sessiondata.getClientId(player.userId) arenaContent = dizhuhallinfo.getArenaMatchProvinceContent( player.userId, int(mixId) if mixId else self._room.roomId, clientId) # 冠军发送Led通知所有其他玩家 ledtext = dizhuled._mk_match_champion_rich_text( player.userName, arenaContent.get('name') if arenaContent else roomName, arenaContent.get('rewardShow') if arenaContent else self._room.roomConf.get('rewardShow', rewardDesc)) LedUtil.sendLed(ledtext, 'global') sequence = int(player.matchInst.instId.split('.')[1]) matchutil.report_bi_game_event( 'MATCH_FINISH', player.userId, player.matchInst.matchId, 0, sequence, 0, 0, 0, [int(player.mixId) if player.mixId else 255], 'match_end')
def notifyMatchOver(self, player, reason, rankRewards): ''' 通知用户比赛结束了 ''' try: if (reason == MatchFinishReason.USER_WIN or reason == MatchFinishReason.USER_LOSER): try: event_remote.publishMatchWinloseEvent( self._room.gameId, player.userId, self._room.match.matchId, reason == MatchFinishReason.USER_WIN, player.rank, player.group.startPlayerCount, rankRewards.conf if rankRewards else None) from dizhu.entity.matchhistory import MatchHistoryHandler MatchHistoryHandler.onMatchOver( player.userId, player.group.matchConf.recordId, player.rank, reason == MatchFinishReason.USER_WIN, rankRewards.conf if rankRewards else None, player.group.isGrouping) except: self._logger.error('PlayerNotifierDizhu.notifyMatchOver', 'userId=', player.userId, 'groupId=', player.group.groupId, 'reason=', reason, 'rankRewards=', rankRewards.rewards) # 比赛记录保存 try: event = { 'gameId': self._room.gameId, 'userId': player.userId, 'matchId': self._room.match.matchId, 'rank': player.rank, 'isGroup': 1 if player.group.isGrouping else 0 } MatchRecord.updateAndSaveRecord(event) except: self._logger.error('PlayerNotifierDizhu.notifyMatchOver', 'gameId=', self._room.gameId, 'userId=', player.userId, 'reason=', reason, 'matchId=', self._room.match.matchId, 'rank=', player.rank) msg = MsgPack() msg.setCmd('m_over') msg.setResult('gameId', self._room.gameId) msg.setResult('roomId', self._room.bigRoomId) msg.setResult('userId', player.userId) msg.setResult('reason', reason) msg.setResult('rank', player.rank) try: msg.setResult('beatDownUser', player.beatDownUserName) except: ftlog.debug('NobeatDownUser group match') ftlog.exception() if rankRewards or reason == MatchFinishReason.USER_WIN: msg.setResult('info', buildWinInfo(self._room, player, rankRewards)) if rankRewards.todotask: msg.setResult('todotask', rankRewards.todotask) else: msg.setResult('info', buildLoserInfo(self._room, player)) msg.setResult( 'mucount', player.group.startPlayerCount if player.group.isGrouping else player.group.totalPlayerCount) msg.setResult('date', str(datetime.now().date().today())) msg.setResult('time', time.strftime('%H:%M', time.localtime(time.time()))) msg.setResult('addInfo', '') rewardDesc = '' if rankRewards: from dizhu.bigmatch.match import BigMatch msg.setResult('reward', BigMatch.buildRewards(rankRewards)) rewardDesc = BigMatch.buildRewardsDesc(rankRewards) if rewardDesc: msg.setResult('rewardDesc', rewardDesc) msg.setResult('mname', getMatchName(self._room, player)) record = MatchRecord.loadRecord(self._room.gameId, player.userId, self._room.match.matchId) if record: msg.setResult( 'mrecord', { 'bestRank': record.bestRank, 'bestRankDate': record.bestRankDate, 'isGroup': record.isGroup, 'crownCount': record.crownCount, 'playCount': record.playCount }) else: from dizhu.activities.toolbox import Tool msg.setResult( 'mrecord', { 'bestRank': player.rank, 'bestRankDate': Tool.datetimeToTimestamp( datetime.now()), 'isGroup': 1 if player.group.isGrouping else 0, 'crownCount': 1 if player.rank == 1 else 0, 'playCount': 1 }) try: # 设置奖状分享的todotask diplomaShare shareTodoTask = dizhudiplomashare.buildDiplomaShare( player.userName, getMatchName(self._room, player), player.rank, rewardDesc, player.userId) if shareTodoTask: msg.setResult('shareTodoTask', shareTodoTask) except: ftlog.debug('NobeatDownUser group match') ftlog.exception() router.sendToUser(msg, player.userId) if reason in (MatchFinishReason.USER_NOT_ENOUGH, MatchFinishReason.RESOURCE_NOT_ENOUGH): mo = MsgPack() mo.setCmd('m_signs') mo.setResult('gameId', self._room.gameId) mo.setResult('roomId', self._room.bigRoomId) mo.setResult('userId', player.userId) mo.setResult('signs', {self._room.bigRoomId: 0}) router.sendToUser(mo, player.userId) if player.rank == 1 and self._room.roomConf.get('championLed'): ledtext = '玩家%s在斗地主"%s"中过五关斩六将夺得冠军,获得%s!' % ( player.userName, self._room.roomConf['name'], rewardDesc) user_remote.sendHallLed(DIZHU_GAMEID, ledtext, 1, 'global', []) sequence = int(player.group.instId.split('.')[1]) self.report_bi_game_event("MATCH_FINISH", player.userId, player.group.matchId, 0, sequence, 0, 0, 0, [], 'match_end') #_stage.matchingId except: self._logger.error('PlayerNotifierDizhu.notifyMatchOver', 'userId=', player.userId, 'groupId=', player.group.groupId, 'reason=', reason, 'rankRewards=', rankRewards.rewards if rankRewards else None)