Example #1
0
 def buildSuccessMessagePack(cls, userId, itemconf):
     '''
     构建抽奖成功的result结果
     @param: itemconf - 抽到的奖励项
     '''
     return {'success':True, 'message': cls.buildLuckyDrawMessage(itemconf),
             'name': UserInfo.getNickname(userId), 'mychip': UserInfo.getChip(userId)}
Example #2
0
    def onUserLuckyDraw(cls, userId, roomId):
        '''
        热身系统:抽奖处理
        '''
        ftlog.debug('WarmUpSystem.onUserLuckyDraw',
                    'userId=', userId,
                    'roomId=', roomId)

        global warmupLotteryPool
        if not warmupLotteryPool:
            warmupLotteryPool = WarmUpSystemLotteryPool()

        ftlog.debug('WarmUpSystem.onUserLuckyDraw',
                    'userId=', userId,
                    'warmupLotteryPool.prizeList=', warmupLotteryPool.lotteryPool.prizeList)


        ## 处理抽奖花费不足
        if not WarmUpSystemHelper.checkAssetsEnough(userId):
            return {'success':False, 'mychip': UserInfo.getChip(userId)}

        ## 处理抽奖CD
        if not CountingTimer.checkCooldownFinish(userId):
            return {'success':False, 'mychip': UserInfo.getChip(userId)}

        ## 消耗抽奖花费
        if not WarmUpSystemHelper.consumeLuckyDrawExpenses(userId):
            return {'success':False, 'mychip': UserInfo.getChip(userId)}

        chooseItemConfigure = warmupLotteryPool.randomGetPoolItem()
        ftlog.debug('WarmUpSystem.onUserLuckyDraw',
                    'userId=', userId,
                    'chooseItemConfigure=', chooseItemConfigure)

        ## 重置CD时间
        CountingTimer.resetCounting(userId)

        ## 抽奖未抽中
        chooseitemId = chooseItemConfigure.get('itemId')
        if not chooseitemId or len(chooseitemId) <= 0:
            return WarmUpSystemHelper.buildSuccessMessagePack(userId, chooseItemConfigure)

        ## 发送抽奖奖励
        prizeMail = WarmUpSystemHelper.buildLuckyDrawMailMessage(chooseItemConfigure, roomId)
        UserBag.sendAssetsToUser(6, userId, chooseItemConfigure, BIEVENT_ID, prizeMail)

        ## 添加消息到抽奖记录中
        LuckyDrawRecorder.pushRecord(LuckyDrawRecorder.buildRecord(userId, chooseItemConfigure))

        return WarmUpSystemHelper.buildSuccessMessagePack(userId, chooseItemConfigure)
Example #3
0
    def sendLedText(self, activityGameId, userId, prize):
        ledsMap = Tool.dictGet(self._clientConf, 'config.server.ledsMap', {})
        prizes = Tool.dictGet(self._clientConf, 'config.server.prizes', [])

        for item in prizes:
            # 根据奖励itemId找到奖励配置
            if item['itemId'] != prize['itemId']:
                continue
            # 获取led发送的配置
            ledItem = ledsMap.get(item.get('ledKey'))
            if not ledItem:
                continue
            # 查看是否满足LED发送条件
            if ledItem.get('minCount', 0) > prize['count']:
                continue
            text = ledItem.get('text')
            if not text:
                continue
            prizeContent = hallitem.buildContent(prize['itemId'],
                                                 prize['count'], True)
            ledtext = strutil.replaceParams(
                text, {
                    'nickname': UserInfo.getNickname(userId),
                    'prizeContent': prizeContent
                })
            hallled.sendLed(activityGameId, ledtext, 0, scope='hall6')
            if ftlog.is_debug():
                ftlog.debug('LuckyMoneyNew.sendLedText', 'activityGameId=',
                            activityGameId, 'activityId=',
                            self._clientConf['id'], 'userId=', userId,
                            'ledtext=', ledtext)
            break
Example #4
0
 def getRankingListByRankNumberList(cls, rankingMax, rankNumberList):
     '''
     获得指定排名的玩家和分数
     :param rankingMax: 最大排名,加载的TopN人数
     :param rankNumberList: 指定名次的列表, 从1开始[1,2,3,10,50]
     '''
     issueNum = cls.getYesterdayRankingIssueNumber()
     replays = replay_service.getTopNReplayWithViewsCount(issueNum, rankingMax)
     if ftlog.is_debug():
         ftlog.debug('RankingProxy.getRankingListByRankNumberList:',
                     'issueNum=', issueNum,
                     'rankingMax=', rankingMax,
                     'rankNumberList=', rankNumberList,
                     'replays.length', len(replays))
     
     rankingList = []
     for index, item in enumerate(replays):
         replay, replayCount = item
         rankNumber = index + 1
         if rankNumber in rankNumberList: 
             if ftlog.is_debug():
                 ftlog.debug('RankingProxy.getRankingListByRankNumberList',
                             'replay.userId=', replay.userId,
                             'replayCount=', replayCount)
             rankingList.append({
                 'rankNumber': rankNumber,
                 'nickname': UserInfo.getNickname(replay.userId),
                 'rankValue': replayCount,
             })
     if ftlog.is_debug():
         ftlog.debug('RankingProxy.getRankingListByRankNumberList:rankingList=', rankingList)
     return rankingList
Example #5
0
    def onUpdate(cls):
        ftlog.debug(
            "RankingPriorityLedSender.onUpdate", "cls.currentRankingUser="******"cls.rankingRewardList=",
            cls.rankingRewardList, "cls.ledFormatText=", cls.ledFormatText,
            "ifok=",
            not not (not cls.currentRankingUser or not cls.ledFormatText
                     or not cls.rankingRewardList))

        if not cls.currentRankingUser or not cls.ledFormatText or not cls.rankingRewardList:
            cls.currentRankingUser = None
            cls.oldRankingUser = None
            cls.loopTimerCounter = 0
            if cls.loopTimer:
                cls.loopTimer.cancel()
            return
        ftlog.debug("RankingPriorityLedSender.onUpdate", "userId=",
                    cls.currentRankingUser.userId, "cls.loopTimerCounter",
                    cls.loopTimerCounter)

        helper = RankingRewardHelper(cls.currentRankingUser.userId,
                                     cls.rankingRewardList)
        reachedlist = helper.getReachedConfList()
        currentconf = {}
        if reachedlist and len(reachedlist) > 0:
            currentconf = reachedlist[-1]
        dictionary = {}
        dictionary['ranking_current_item'] = Tool.dictGet(
            currentconf, 'rewardContent.desc')
        dictionary['newuser_nickname'] = UserInfo.getNickname(
            cls.currentRankingUser.userId)
        dictionary['newuser_ranknumber'] = str(
            DumplingsUtil.getRankingWithUserId(cls.currentRankingUser.userId))
        dictionary['olduser_nickname'] = UserInfo.getNickname(
            cls.oldRankingUser.userId)
        led = strutil.replaceParams(cls.ledFormatText, dictionary)
        Tool.sendLed(led)

        cls.loopTimerCounter += 1
        if cls.loopTimerCounter >= 5:
            ftlog.debug("RankingPriorityLedSender.onUpdate ",
                        "cls.loopTimerCounter>=5:", "userId=",
                        cls.currentRankingUser.userId)
            cls.currentRankingUser = None
            cls.oldRankingUser = None
            cls.loopTimer.cancel()
            cls.loopTimerCounter = 0
Example #6
0
    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
Example #7
0
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
Example #8
0
    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 _checkExpectedUser(userId, behaviourConf):
    if not behaviourConf or behaviourConf.get('open', 0) != 1:
        return False

    # 过滤clientId
    _, intClientId = sessiondata.getClientIdNum(userId)
    intClientIds = behaviourConf.get('intClientIds', [])
    if intClientId in intClientIds:
        return False

    # 过滤注册时间在7天以内的用户
    timestamp = pktimestamp.getCurrentTimestamp()
    if UserInfo.getRegisterDays(userId, timestamp) <= 7:
        return False
    return True
Example #10
0
 def onGetRecordMessage(cls, userId, number):
     '''
     获得抽奖记录处理
     '''
     messageList = LuckyDrawRecorder.getRecordWithNumber(number)
     ftlog.debug('WarmUpSystem.onGetRecordMessage',
                 'userId=', userId,
                 'number=', number,
                 'messageList=', messageList)
     return {
         'messages':messageList or [],
         'cd': CountingTimer.getConfigureRequireCooldownSeconds(),
         'chip': WarmUpSystemHelper.getLuckyDrawExpenses().get('count'), # 只会消耗金币
         'mychip': UserInfo.getChip(userId)
     }
Example #11
0
    def sendLedIfNeed(self, userId, itemconf, count):
        '''
        如果满足情况则,发送LED
        :param itemconf: 红包奖励配置项{"type":"random.fixed", "itemId": "item:2003", "desc":"记牌器", "num":500, "count":1, "led": "led1"}
        :param count: 拆红包真实领取的物品个数
        :return: Bool, 是否发送
        '''
        settingkey = itemconf.get("led", False)
        if not settingkey:
            return False

        ftlog.debug("TYActivityDdzRedEnvelope.sendLedIfNeed: settingkey=",
                    settingkey)
        clientconf = self._clientConf
        settingmap = Tool.dictGet(clientconf, "config.activate.ledSetting")
        if not settingmap:
            return False
        ftlog.debug("TYActivityDdzRedEnvelope.sendLedIfNeed: settingmap=",
                    settingmap)

        setting = settingmap.get(settingkey)
        if not setting:
            return False
        ftlog.debug("TYActivityDdzRedEnvelope.sendLedIfNeed: setting=",
                    setting)

        text = setting.get("text")
        if (not text) or len(text) <= 0:
            return False

        ftlog.debug("TYActivityDdzRedEnvelope.sendLedIfNeed: text=", text,
                    "mincount", setting.get("min", 0))
        mincount = setting.get("min", 0)
        if count >= mincount:
            leddict = {
                "assets": str(itemconf.get('desc')),
                "count": str(count),
                "userId": str(userId),
                "nickname": str(UserInfo.getNickname(userId))
            }
            text = strutil.replaceParams(text, leddict)
            Tool.sendLed(text)
            return True
        return False
Example #12
0
def can_ios_tablefinish_fivestar(event):
    if not event.winlose.isWin:
        return False

    # 玩家在高倍场馆单局倍数超过128倍并获胜
    if event.winlose.windoubles >= 128:
        return True

    # 账号注册时间大于五天、游戏局数超过20局的玩家,连续获胜3局时
    timestamp = pktimestamp.getCurrentTimestamp()
    if UserInfo.getRegisterDays(event.userId, timestamp) > 5:
        winrate, winstreak = gamedata.getGameAttrs(event.userId, 6, ['winrate', 'winstreak'])
        winrate = strutil.loads(winrate, ignoreException=True, execptionValue={'pt':0, 'wt':0})
        try:
            winstreak = 0 if winstreak is None else int(winstreak)
        except:
            winstreak = 0
        if winrate.get('pt', 0) > 20 and winstreak == 3:
            return True
    return False
Example #13
0
    def _doReport(cls, gameId, userId, otherPlayerId, reasons):
        mo = MsgPack()
        mo.setCmd('dizhu')
        mo.setResult('action', 'user_report')
        # 检测举报条件
        reportDetail = gamedata.getGameAttr(userId, gameId, 'report')
        reportDetail = strutil.loads(reportDetail) if reportDetail else {}
        reportCount = reportDetail.setdefault('count', 0)
        reportTimestamp = reportDetail.setdefault('timestamp', 1356969600)
        currentTimestamp = pktimestamp.getCurrentTimestamp()

        if not pktimestamp.is_same_day(currentTimestamp, reportTimestamp):
            reportDetail['count'] = 0
        else:
            if reportCount >= 10:
                mo.setError(1, '举报过于频繁,系统正在核实举报信息')
                router.sendToUser(mo, userId)
                return

            if currentTimestamp - reportTimestamp < 180:
                mo.setError(2, '举报过于频繁,系统正在核实举报信息')
                mo.setResult('remaining',
                             180 - (currentTimestamp - reportTimestamp))
                router.sendToUser(mo, userId)
                return

        # 发送消息给举报者, 增加举报者举报次数
        reportDetail['count'] += 1
        reportDetail['timestamp'] = currentTimestamp
        gamedata.setGameAttr(userId, gameId, 'report',
                             strutil.dumps(reportDetail))
        reportStr = ''
        for reason in reasons:
            reportStr += cls._getTipByReason(reason)
        tip = '举报反馈:\n  您举报了玩家【%s】。\n  我们会核实原因,进行相应处理。' % (
            UserInfo.getNickname(otherPlayerId))
        mo.setResult('success', 1)
        mo.setResult('tip', tip)
        router.sendToUser(mo, userId)
        pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, tip)

        # 发送消息给被举报者,只有在原因①/③的情况下,被举报玩家才会收到信息,若被举报玩家同时因①③被举报,则优先使用①的被举报文本。
        # 增加被举报者举报次数
        reportedDetail = gamedata.getGameAttr(otherPlayerId, gameId,
                                              'reported')
        reportedDetail = strutil.loads(
            reportedDetail) if reportedDetail else {}
        reportedDetail.setdefault('count', 0)

        for r in reasons:
            if r in [UserReportReason.NEGATIVE, UserReportReason.OFFLINE]:
                reportedDetail['count'] += 1
                if not pktimestamp.is_same_day(currentTimestamp,
                                               reportTimestamp):
                    reportedDetail.setdefault(str(r), 0)
                    reportedDetail[str(r)] = 0
                else:
                    reportedDetail.setdefault(str(r), 0)
                    reportedDetail[str(r)] += 1
        gamedata.setGameAttr(otherPlayerId, gameId, 'reported',
                             strutil.dumps(reportedDetail))

        tip = ''
        if UserReportReason.NEGATIVE in reasons:
            tip = '举报信息:\n  您因<%s>被玩家举报。\n  系统已记录,下次要认真一些喔~' % cls._getTipByReason(
                UserReportReason.NEGATIVE)
            if reportedDetail.setdefault(str(UserReportReason.NEGATIVE),
                                         0) > 5:
                tip = ''

        if UserReportReason.OFFLINE in reasons:
            if reportedDetail.setdefault(str(UserReportReason.OFFLINE), 0) > 5:
                tip = tip
            else:
                tip = '举报信息:\n  您因<%s>被玩家举报。\n  快去找一个好的网络环境吧~' % cls._getTipByReason(
                    UserReportReason.OFFLINE)

        if tip:
            pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM,
                           otherPlayerId, tip)
Example #14
0
def doInitTablePlayerDatas(userId, roomId, **kwargs):
    gameId = DIZHU_GAMEID
    clientId = sessiondata.getClientId(userId)
    devId = sessiondata.getDeviceId(userId)
    clientIp = sessiondata.getClientIp(userId)

    exp, suaddress, susex, suname, sucoin, charm = userdata.getAttrs(
        userId, ['exp', 'address', 'sex', 'name', 'coin', 'charm'])
    sugold, slevel, swinrate, winchips, starid, winstreak, lastwinstreak, maxwinstreak, winrate2, firstWin = gamedata.getGameAttrs(
        userId, gameId, [
            'gold', 'level', 'winrate', 'winchips', 'starid', 'winstreak',
            'lastwinstreak', 'maxwinstreak', 'winrate2', 'firstWin'
        ])

    swinrate = strutil.loads(swinrate,
                             ignoreException=True,
                             execptionValue={
                                 'pt': 0,
                                 'wt': 0
                             })
    winrate2 = strutil.loads(winrate2,
                             ignoreException=True,
                             execptionValue={
                                 'pt': 0,
                                 'wt': 0
                             })
    firstWin = strutil.loads(firstWin, ignoreException=True, execptionValue={})
    suchip = userchip.getChip(userId)
    bigRoomId = strutil.getBigRoomIdFromInstanceRoomId(roomId)
    mixConfRoomId = kwargs.get('mixConf', {}).get('roomId')
    tbplaytimes, tbplaycount = treasurebox.getTreasureBoxState(
        gameId, userId, mixConfRoomId or bigRoomId)
    try:
        supic, isBeauty = halluser.getUserHeadUrl(userId, clientId)
    except:
        supic, isBeauty = '', False
    slevel = recoverUserAttr(slevel, int, 0)

    datas = {}
    datas['uid'] = userId
    datas['clientId'] = clientId
    datas['devId'] = recoverUserAttr(devId, str, '')
    datas['clientIp'] = recoverUserAttr(clientIp, str, '')
    datas['address'] = recoverUserAttr(suaddress, unicode, '')
    datas['sex'] = recoverUserAttr(susex, int, 0)
    datas['name'] = recoverUserAttr(suname, unicode, '')
    datas['coin'] = recoverUserAttr(sucoin, int, 0)
    datas['headUrl'] = ''
    datas['purl'] = supic
    datas['isBeauty'] = isBeauty
    datas['chip'] = suchip
    datas['exp'] = recoverUserAttr(exp, int, 0)
    datas['gold'] = recoverUserAttr(sugold, int, 0)
    datas['vipzuan'] = []
    datas['tbc'] = tbplaycount
    datas['tbt'] = tbplaytimes
    datas['level'] = slevel
    datas['wins'] = swinrate.get('wt', 0)
    datas['plays'] = swinrate.get('pt', 0)
    datas['winchips'] = recoverUserAttr(winchips, int, 0)
    datas['nextexp'] = 0
    datas['title'] = ''
    datas['medals'] = []
    datas['skillScoreInfo'] = skillscore.buildUserSkillScoreInfo(
        skillscore.getUserSkillScore(gameId, userId))
    datas['charm'] = 0 if charm == None else recoverUserAttr(charm, int, 0)
    datas['vipInfo'] = hallvip.userVipSystem.getVipInfo(userId)
    datas['starid'] = 0 if starid == None else recoverUserAttr(starid, int, 0)
    datas['winstreak'] = 0 if winstreak == None else recoverUserAttr(
        winstreak, int, 0)
    datas['lastwinstreak'] = 0 if lastwinstreak == None else recoverUserAttr(
        lastwinstreak, int, 0)
    datas['maxwinstreak'] = 0 if maxwinstreak == None else recoverUserAttr(
        maxwinstreak, int, 0)
    datas['gameClientVer'] = gamesession.getGameClientVer(gameId, userId)
    datas['winrate2'] = winrate2
    datas['firstWin'] = firstWin

    # TODO 查询用户增值位
    datas['wearedItems'] = []
    userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
    timestamp = pktimestamp.getCurrentTimestamp()
    memberCardItem = userBag.getItemByKindId(hallitem.ITEM_MEMBER_NEW_KIND_ID)
    datas[
        'memberExpires'] = memberCardItem.expiresTime if memberCardItem else 0
    datas['registerDays'] = UserInfo.getRegisterDays(userId, timestamp)
    item = userBag.getItemByKindId(hallitem.ITEM_CARD_NOTE_KIND_ID)

    # 新用户的计次记牌器
    newUserReward = configure.getGameJson(gameId, 'login.reward',
                                          {}).get('newUserReward')
    if newUserReward:
        if newUserReward.get('open', 0):
            cardNoteCount = newUserReward.get('cardNoteCount', 0)
            if cardNoteCount:
                pt = swinrate.get('pt', 0)
                if cardNoteCount - pt >= 1:
                    datas['cardNotCount'] = max(1, cardNoteCount - pt)

    if item and not item.isDied(timestamp):
        datas['cardNotCount'] = max(1, item.balance(timestamp))

    if ftlog.is_debug():
        ftlog.debug('table_remote.doInitTablePlayerDatas', 'userId=', userId,
                    'clientId=', clientId, 'datas=', datas)
    return datas
Example #15
0
 def buildRecord(cls, userId, itemconf):
     return {'message': WarmUpSystemHelper.buildLuckyDrawMessage(itemconf), 'name': UserInfo.getNickname(userId)}
Example #16
0
    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
Example #17
0
    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
Example #18
0
    def handleRequestGetting(self, model, userId, poolItem):
        '''
        已经投入资本,领取奖励
        :param userId:
        :return:
        '''
        clientconf = strutil.deepcopy(self._clientConf)
        serverconf = self._serverConf
        uniquekey = Utility.buildUniqueKey(serverconf)
        ftlog.debug('WishingWell.handleRequestGetting:start',
                    'userId=', userId,
                    'model=', model.dict())

        ## 判断计时是否完成
        countingSeconds = model.getCountingSeconds()
        if countingSeconds < poolItem.get('duration', 0):  ## 计时未完成
            return Utility.buildError(Tool.dictGet(clientconf, 'config.countingDownError'))

        ## 发送用户奖励
        led = Tool.dictGet(clientconf, 'config.led')
        mail = Tool.dictGet(clientconf, 'config.mail')
        rewardconf = poolItem.get('reward', {})
        rtype = rewardconf.get('type', 'fixed')
        clz = self.rewardHandlerMap[rtype]
        ftlog.debug('WishingWell.handleRequestGetting:send',
                    'userId=', userId,
                    'rewardconf=', rewardconf,
                    'rtype=', rtype,
                    'clz=', clz)
        if not clz:
            return Utility.buildError(None)
        sendcount = clz(rewardconf, mail).sendToUser(userId)

        ## 是否触发LED
        ledTrigger = poolItem.get('ledTrigger', -1)
        if ledTrigger>=0 and ledTrigger<=sendcount:
            nickname = UserInfo.getNickname(userId)
            Tool.sendLed(strutil.replaceParams(led, {'nickname':nickname}))
        ftlog.debug('WishingWell.handleRequestGetting:led',
                    'userId=', userId,
                    'ledTrigger=', ledTrigger,
                    'sendcount=', sendcount,
                    'led-trigger-ok', (ledTrigger>=0 and ledTrigger<=sendcount))

        ftlog.info('WishingWell.handleRequestGetting, ',
                   'userId', userId,
                   'poolstepindex', model.poolStepIndex,
                   'sendcount', sendcount,
                   'model=', model.dict())

        model.isAlreadyPutted = False
        model.poolStepIndex += 1
        model.dumpsToRedis(userId, uniquekey)
        ftlog.debug('WishingWell.handleRequestGetting:end',
                    'userId=', userId,
                    'model=', model.dict())

        response = self.getActivityUserStatus(userId, model)
        gettingSuccess = Tool.dictGet(clientconf, 'config.gettingSuccess')
        rewardDescription = strutil.replaceParams(Tool.dictGet(poolItem, 'reward.desc'), {'count': sendcount})
        if gettingSuccess and len(gettingSuccess) > 0:
            response['message'] = strutil.replaceParams(gettingSuccess, {'assets_reward_desc':rewardDescription})
        response['operate'] = 'getting'
        return response