Exemplo n.º 1
0
    def __init__(self, dao, clientConfig, serverConfig):
        super(self.__class__, self).__init__(dao, clientConfig, serverConfig)
        self._dao = dao
        self._serverConf = serverConfig
        self._clientConf = clientConfig
        self._dataWrapper = DataWrapper(serverConfig)

        ftlog.debug("TYActivityDdzRedEnvelope.__init__",
                    clientConfig.get('id'), self.checkOperative(),
                    serverConfig, clientConfig)

        if not self.checkOperative():
            return

        if not _redenvelopeWrapper:
            ftlog.debug("TYActivityDdzRedEnvelope. global _redenvelopeWrapper")
            global _redenvelopeWrapper
            general = Tool.dictGet(clientConfig,
                                   "config.activate.generalRedEnvelope")
            vip = Tool.dictGet(clientConfig, "config.activate.vipRedEnvelope")
            _redenvelopeWrapper = RedEnvelopeWrapper(general, vip)

        if not DdzRedEnvelope._timelist:
            ftlog.debug("TYActivityDdzRedEnvelope. DdzRedEnvelope._timelist")
            timelist = Tool.dictGet(clientConfig, "config.activate.timeList")
            datetime_start = datetime.strptime(serverConfig.get("start"),
                                               "%Y-%m-%d %H:%M:%S")
            datetime_end = datetime.strptime(serverConfig.get("end"),
                                             "%Y-%m-%d %H:%M:%S")
            DdzRedEnvelope._timelist = self.getTimePointListInRange(
                timelist, datetime_start, datetime_end)
            DdzRedEnvelope._datetime_start = datetime_start
            DdzRedEnvelope._datetime_end = datetime_end

            DdzRedEnvelope.onHeartBeat(None)
Exemplo n.º 2
0
    def __init__(self, dao, clientConf, serverConf):
        super(self.__class__, self).__init__(dao, clientConf, serverConf)

        # 红包池key,用于区分不同红包池,每个活动对应不同(直接使用活动ID)
        self.poolId = clientConf['id']

        # 配置的活动游戏ID,用于存储用户数据,金流日志记录等
        self.activityGameId = Tool.dictGet(clientConf,
                                           'config.server.activityGameId', 6)

        # 红包开启时间列表
        timesConf = Tool.dictGet(clientConf, 'config.server.times', [])
        self.openList = OpenDurationList(timesConf, serverConf)

        # 红包发布对象,用于定时发布红包
        self.publisher = LuckyMoneyPublisher(clientConf, self.openList,
                                             self.poolId)

        # 注册监听事件
        self.registerEvents()

        if ftlog.is_debug():
            ftlog.debug('LuckyMoneyNew.__init__:'
                        'activityId=', clientConf['id'], 'openList=',
                        [(item.start, item.end)
                         for item in self.openList.itemList])
Exemplo n.º 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
Exemplo n.º 4
0
    def recommendProductIfCan(self, gameId, userId):
        # 没有配置推荐商品,则不推荐
        payOrder = Tool.dictGet(self._clientConf, 'config.server.payOrder')
        if not payOrder:
            return False

        clientId = sessiondata.getClientId(userId)
        product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId,
                                                     payOrder)
        ftlog.debug('FunAct.recommendProductIfCan:', 'userId=', userId,
                    'product=', product)
        # 没有在货架中找到商品
        if not product:
            return False

        translateMap = {
            'product.displayName': product.displayName,
            'product.price': product.price,
            'count': payOrder.get('contains', {}).get('count', 0)
        }
        desc = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipDesc')
        note = Tool.dictGet(self._clientConf, 'config.server.lessBuyChipNote')
        desc = strutil.replaceParams(desc, translateMap)
        note = strutil.replaceParams(note, translateMap)
        todotask = TodoTaskLessBuyOrder(desc, None, note, product)
        TodoTaskHelper.sendTodoTask(gameId, userId, todotask)
        return True
Exemplo n.º 5
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
Exemplo n.º 6
0
 def getItemConf(self, clientconf, iteminfo):
     isvip = iteminfo.get('isVipItem', False)
     conf = Tool.dictGet(clientconf, 'config.activate.generalRedEnvelope')
     if isvip:
         conf = Tool.dictGet(clientconf, 'config.activate.vipRedEnvelope')
     for x in conf:
         if x.get('itemId') == iteminfo.get('itemId'):
             return x
     return False
Exemplo n.º 7
0
    def onActionBetChip(self, userId, betChip, isLeft, issueNumber):
        ftlog.debug('BetGuess.onActionBetChip:', 'userId=', userId, 'betChip=',
                    betChip, 'isLeft=', isLeft, 'issueNumber=', issueNumber)
        clientconf = self._clientConf
        activityGameId = clientconf.get('activityGameId')
        issueNumberNow = self.issueCalculator.getCurrentIssueNumber()
        ftlog.debug('BetGuess.onActionBetChip:', 'userId=', userId,
                    'issueNumberNow=', issueNumberNow, 'issueNumber=',
                    issueNumber)

        # 参数合理性判断,不合理直接忽略
        if betChip <= 0 or isLeft == None:
            return self.buildActivityInfo(userId)
        # 没有当前一期的竞猜
        if not issueNumberNow:
            return self.makeResponseMessage(
                userId, {
                    'message':
                    Tool.dictGet(clientconf, 'config.server.allIssueOutdate')
                })
        # 客户端展示的期号与当前不一致,强制刷新
        if issueNumber != issueNumberNow:
            return self.makeResponseMessage(userId, {
                'message':
                Tool.dictGet(clientconf, 'config.server.issueOutdate')
            })

        # 若推荐商品,则代表金币不足,直接返回
        if self.recommendProductIfNeed(activityGameId, userId, betChip):
            return self.buildActivityInfo(userId)

        # 消耗用户金币,增加用户存储的活动数据金币
        userModel = ActivityUserModel.loadModel(userId, activityGameId,
                                                self.getid())
        err = self.userBetChip(userId, activityGameId, issueNumber, userModel,
                               isLeft, betChip)
        if err:
            return self.makeResponseMessage(userId, {'message': err})

        # 记录玩家
        UserRecorder.addUser(userId, activityGameId, self.getid(), issueNumber)

        # 增加活动奖池记录数据
        activityModel = ActivityModel.loadModel(activityGameId, self.getid(),
                                                issueNumber)
        activityModel.incrChip(isLeft, betChip)
        ftlog.info('BetGuess.onActionBetChip', 'userId=', userId,
                   'activityGameId=', activityGameId, 'activityId=',
                   self.getid(), 'issueNumber=', issueNumber,
                   'activityModel.resultState=', activityModel.resultState,
                   'activityModel.countChipLeft=', activityModel.countChipLeft,
                   'activityModel.countChipRight=',
                   activityModel.countChipRight)

        return self.buildActivityInfo(userId, activityModel, userModel)
Exemplo n.º 8
0
 def calculateScore(cls, rmb, dashifen):
     '''
     计算排行分数
     :param rmb: 活动期间RMB消费总数
     :param dashifen: 活动期间大师分增长数量
     '''
     actconf = cls.getActivityConf()
     dashifen_ratio = Tool.dictGet(actconf,
                                   'config.activate.dashifen_ratio', 0)
     charge_ratio = Tool.dictGet(actconf, 'config.activate.charge_ratio', 0)
     return dashifen * dashifen_ratio + rmb * charge_ratio
Exemplo n.º 9
0
 def markGet(self, userId, datetime, assets):
     '''
     记录领取红包
     :param datetime: 标记的领取红包的时间点
     '''
     rediskey = self.getRedisKey()
     dictobj = Redis.readJson(userId, rediskey)
     key = "get.%s" % str(datetime)
     Tool.dictSet(dictobj, key, assets)
     Redis.writeJson(userId, rediskey, dictobj)
     ftlog.debug("DataWrapper.makeGet: userId=", userId, "key=", key,
                 "datetime=", str(datetime), "dictobj=", dictobj)
Exemplo n.º 10
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
Exemplo n.º 11
0
    def _generatePackets(cls, bankId, issue):
        '''
        生成红包,并存储到redis中,多进程利用redis同步生成的红包数据
        '''
        clientconf = ConfigDatabase.getClientConfig(bankId)
        nor_items = Tool.dictGet(clientconf,
                                 "config.activate.generalRedEnvelope")
        vip_items = Tool.dictGet(clientconf, "config.activate.vipRedEnvelope")

        # {"user:coupon":[...], "item:1007":[...], ...}
        nor_packets = {}
        nor_packets_num = {}  # 每个道具的数量
        for item in nor_items:
            itemtype = item.get("type")
            itemId = item.get("itemId")
            num = item.get("num")
            if itemtype == "random.split":
                total = item.get("total")
                minv = item.get("min")
                nor_packets[
                    itemId] = Random.getNormalDistributionRandomSequence(
                        total, minv, num)
            elif itemtype == "random.fixed":
                count = item.get("count")
                nor_packets[itemId] = [count for _ in xrange(num)]
            nor_packets_num[itemId] = num

        # {"user:coupon":[...], "item:1007":[...], ...}
        vip_packets = {}
        vip_packets_num = {}  # 每个道具的数量
        for item in vip_items:
            itemtype = item.get("type")
            itemId = item.get("itemId")
            num = item.get("num")
            if itemtype == "random.split":
                total = item.get("total")
                minv = item.get("min")
                vip_packets[
                    itemId] = Random.getNormalDistributionRandomSequence(
                        total, minv, num)
            elif itemtype == "random.fixed":
                count = item.get("count")
                vip_packets[itemId] = [count for _ in xrange(num)]
            vip_packets_num[itemId] = num

        packets_data = {"nor": nor_packets, "vip": vip_packets}
        count_data = {"nor": nor_packets_num, "vip": vip_packets_num}
        data = PacketRedisInterface.setPacketData(bankId, issue, packets_data,
                                                  count_data)
        return json.loads(data)
Exemplo n.º 12
0
 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
Exemplo n.º 13
0
    def getConfigForClient(self, gameId, userId, clientId):
        '''
        获取客户端要用的活动配置,由TYActivitySystemImpl调用
        '''
        clientconf = self._clientConf
        serverconf = self._serverConf
        ftlog.debug("TYActivityDumplings.getConfigForClient: ", "userId=",
                    userId, "gameId=", gameId, "clientId=", clientId,
                    "serverconf=", serverconf, "clientconf=", clientconf)

        rankingId = DumplingsUtil.getRankingId()
        if not rankingId:
            return
        rankingconf = DumplingsUtil.getRankingConfigById(rankingId)
        rewardlist = rankingconf.get('rankRewardList', [])
        RankingPriorityLedSender.rankingRewardList = rewardlist

        actconf = DumplingsUtil.getActivityConf()
        RankingPriorityLedSender.ledFormatText = Tool.dictGet(
            actconf, 'config.activate.ranking.userLed')
        ftlog.debug("TYActivityDumplings.getConfigForClient: ", "userId=",
                    userId, "rewardlist=", rewardlist, "ledFormatText=",
                    RankingPriorityLedSender.ledFormatText)

        return clientconf
Exemplo n.º 14
0
 def __init__(self):
     ## 许愿池配置列表的指向当前可以进行的index
     self.poolStepIndex = 0
     ## 是否已经投入
     self.isAlreadyPutted = False
     ## 计时
     self.lastTimestamp = Tool.datetimeToTimestamp(datetime.now())
Exemplo n.º 15
0
    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
Exemplo n.º 16
0
    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
Exemplo n.º 17
0
    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
Exemplo n.º 18
0
 def isOutdate(cls):
     '''
     获得是否过期,使用game/6/activity/0.json中的配置判断
     '''
     dizhuconf = cls.getDdzActivityConf()
     ftlog.debug("DdzMatchScore.onMatchWinlose: dizhuconf=", dizhuconf)
     return not Tool.checkNow(dizhuconf.get('start_date', '2016-01-01 00:00:00'), dizhuconf.get('end_date', '2016-01-01 00:00:00'))
Exemplo n.º 19
0
    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
Exemplo n.º 20
0
 def isPutIntoButtonOutdate(cls, clientconf):
     '''
     是否投入按钮已经过期,先于活动过期
     :param clientconf:
     :return: True/False
     '''
     buttonconf = Tool.dictGet(clientconf, 'config.putButtonLife', {})
     datetime_start = buttonconf.get('start', '')
     datetime_end = buttonconf.get('end', '')
     ok = not Tool.checkNow(datetime_start, datetime_end)
     ftlog.debug('Utility.isPutIntoButtonOutdate',
                 'buttonconf=', buttonconf,
                 'datetime_start=', datetime_start,
                 'datetime_end=', datetime_end,
                 'ok=', ok)
     return ok
Exemplo n.º 21
0
    def handleRequest(self, msg):
        clientconf = strutil.deepcopy(self._clientConf)
        serverconf = self._serverConf

        userId = msg.getParam('userId')
        activityId = msg.getParam('activityId')
        action = msg.getParam('action')

        ftlog.debug('WishingWell.handleRequest',
                    'userId=', userId,
                    'activityId=', activityId,
                    'action=', action)

        uniquekey = Utility.buildUniqueKey(serverconf)
        model = UserModel().loadsFromRedis(userId, uniquekey)

        if action == 'ddz.wishing.update':
            return self.handleRequestUpdateStatus(model, userId)

        poolItem = Utility.getPoolItemWithStepIndex(clientconf, model.poolStepIndex)
        ftlog.debug('WishingWell.handleRequest',
                    'userId=', userId,
                    'poolItem=', poolItem,
                    'model=', model.dict())

        ## 许愿池已经全部领光
        if not poolItem:
            return Utility.buildError(Tool.dictGet(clientconf, 'config.nothingPoolItemError'))

        ## 已经投入,则逻辑走领取
        if model.isAlreadyPutted:
            return self.handleRequestGetting(model, userId, poolItem)

        ## 未投入,则走投入逻辑
        return self.handleRequestPutting(model, userId, poolItem)
Exemplo n.º 22
0
    def handleRequestPutting(self, model, userId, poolItem):
        '''
        投入资本
        :param userId:
        :return:
        '''
        clientconf = strutil.deepcopy(self._clientConf)
        serverconf = self._serverConf
        uniquekey = Utility.buildUniqueKey(serverconf)
        ftlog.debug('WishingWell.handleRequestPutting:start',
                    'userId=', userId,
                    'model=', model.dict())

        ## 判断许愿池投入按钮是否过期
        if Utility.isPutIntoButtonOutdate(clientconf):
            return Utility.buildError(Tool.dictGet(clientconf, 'config.wishingOverError'))

        ## 许愿消耗费用
        expensesConfig = poolItem.get('expenses')
        expensesItemId = expensesConfig.get('itemId', 'user:chip')
        expensesItemCount = expensesConfig.get('count', 0)
        ftlog.debug('WishingWell.handleRequestPutting:consume',
                    'userId=', userId,
                    'poolItem=', poolItem,
                    'expensesItemId=', expensesItemId,
                    'expensesItemCount=', expensesItemCount)
        if not UserBag.consumeAssetsIfEnough(userId, expensesItemId, expensesItemCount, self.EVENT_ID): ## 费用不足
            return Utility.buildError(Tool.dictGet(clientconf, 'config.expensesNotEnoughError'))

        ## 更新Model
        model.isAlreadyPutted = True
        ## 重置计时,重新开始计时
        model.resetingCounterToCurrentTimestamp()
        model.dumpsToRedis(userId, uniquekey)

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

        response = self.getActivityUserStatus(userId, model)

        puttingSuccess = Tool.dictGet(clientconf, 'config.puttingSuccess')
        if puttingSuccess and len(puttingSuccess) > 0:
            response['message'] = puttingSuccess
        response['operate'] = 'putting'
        return response
Exemplo n.º 23
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
Exemplo n.º 24
0
 def isOutdate(cls):
     '''
     获得是否过期,使用game/6/activity/0.json中的配置判断
     '''
     dizhuconf = cls.getActivityConfig()
     return not Tool.checkNow(
         dizhuconf.get('datetime_start', '2016-01-01 00:00:00'),
         dizhuconf.get('datetime_end', '2016-01-01 00:00:00'))
Exemplo n.º 25
0
 def setUserActivityData(cls, bankId, userId, data):
     '''
     存储玩家活动记录数据,存储在db7/db8中的gamedata:6:userId中
     '''
     conf = ConfigDatabase.getServerConfig(bankId)
     activity_start = conf.get('start')
     key = cls.getGamedataKey(bankId,
                              Tool.datetimeFromString(activity_start))
     Redis.writeJson(userId, key, data)
Exemplo n.º 26
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
Exemplo n.º 27
0
    def getPrizeStatus(self, activityModel, userModelItem):
        ''' 获取发奖状态 '''
        clientconf = self._clientConf

        # 用户数据记录:未发奖
        if activityModel.resultState == activityModel.RESULT_STATE_NONE:
            return Tool.dictGet(clientconf,
                                'config.server.recordCellWaitingResultTip',
                                '未开奖')

        if activityModel.resultState == activityModel.RESULT_STATE_LEFT and userModelItem.leftBetValue > 0:
            return Tool.dictGet(clientconf,
                                'config.server.recordCellResultWinTip', '猜中')
        if activityModel.resultState == activityModel.RESULT_STATE_RIGHT and userModelItem.rightBetValue > 0:
            return Tool.dictGet(clientconf,
                                'config.server.recordCellResultWinTip', '猜中')

        return Tool.dictGet(clientconf,
                            'config.server.recordCellResultLoseTip', '未猜中')
Exemplo n.º 28
0
    def __init__(self, dao, clientConfig, serverConfig):
        super(self.__class__, self).__init__(dao, clientConfig, serverConfig)
        ftlog.debug('BetGuess.__init__')

        issueMap = Tool.dictGet(clientConfig, 'config.issueMap', {})
        ftlog.debug('BetGuess.__init__:issueMap=', issueMap)
        self.issueCalculator = IssueCalculator(issueMap)

        # 注册监听事件
        self.registerEvents()
Exemplo n.º 29
0
 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
Exemplo n.º 30
0
 def getUserActivityData(cls, bankId, userId):
     '''
     获取玩家活动记录数据,存储在db7/db8中的gamedata:6:userId中
     :return: dict
     '''
     conf = ConfigDatabase.getServerConfig(bankId)
     activity_start = conf.get('start')
     key = cls.getGamedataKey(bankId,
                              Tool.datetimeFromString(activity_start))
     return Redis.readJson(userId, key)