Ejemplo n.º 1
0
 def _reloadTasks(self):
     self._taskList = []
     winStreakTaskConf = self.room.roomConf.get('winStreakTask', {})
     for i, reward in enumerate(winStreakTaskConf.get('tasks', [])):
         TYContentItem.decodeFromDict(reward)
         self._taskList.append(WinStreakTask(i, reward))
     self._taskPictures = winStreakTaskConf.get('imgs', [])
Ejemplo n.º 2
0
    def decodeFromDict(self, d):
        self.startRank = d.get('startRank')
        if not isinstance(self.startRank, int):
            raise TYBizConfException(d, 'RankRewardItem.startRank must be int')

        self.endRank = d.get('endRank')
        if not isinstance(self.endRank, int):
            raise TYBizConfException(d, 'RankRewardItem.endRank must be int')

        self.rewardDesc = d.get('rewardDesc')
        if not isstring(self.rewardDesc):
            raise TYBizConfException(d,
                                     'RankRewardItem.rewardDesc must be str')

        self.rewardPic = d.get('rewardPic')
        if not isstring(self.rewardPic):
            raise TYBizConfException(d, 'RankRewardItem.rewardPic must be str')

        rewards = d.get('rewards')
        if not isinstance(rewards, list):
            raise TYBizConfException(d, 'RankRewardItem.rewards must be list')
        try:
            TYContentItem.decodeList(rewards)
        except Exception, e:
            raise TYBizConfException(
                d, 'RankRewardItem.rewards must be list err=%s' % e.message)
Ejemplo n.º 3
0
    def doGetInviteRewardAll(cls, userId):
        status = loadStatus(userId)
        inviteeRewardList = status.inviteeRewardList
        rewardsList = []
        bigReward = None
        save = False
        for index, rewardState in enumerate(inviteeRewardList):
            if rewardState.rewardState == REWARD_STATE_IDEAL:
                rewardState.rewardState = REWARD_STATE_RECEIVED
                save = True
                r = getSimpleInviteRewardByIndex(index)
                if r:
                    rewardsList.append(r)
        if rewardsList:
            contentItems = TYContentItem.decodeList(rewardsList)
            assetList = dizhu_util.sendRewardItems(userId, contentItems, '', 'DIZHU_QIANDAO_REWARD', 0)

        if len(inviteeRewardList) >= len(getSimpleInviteRewardsConf()):
            bigReward = getSimpleInviteBigReward(userId)
            if bigReward:
                contentItems = TYContentItem.decodeList([bigReward])
                assetList = dizhu_util.sendRewardItems(userId, contentItems, '', 'DIZHU_QIANDAO_REWARD', 0)
                if bigReward.get('itemId') == 'user:coupon':
                    TGHall.getEventBus().publishEvent(UserCouponReceiveEvent(9999, userId, bigReward['count'],
                                                                         user_coupon_details.USER_COUPON_INVITE))
                status.bigRewardState = REWARD_STATE_RECEIVED
                save = True
                conf = getSimpleInviteConf()
                if conf.get('switch'):
                    gamedata.setGameAttr(userId, DIZHU_GAMEID, 'firstBigRewards', 1)
        if save:
            saveStatus(status)
        return rewardsList, bigReward
Ejemplo n.º 4
0
    def _sendActiveReward(self, userId, rewardKind, scheduleId):
        # 发奖接口
        if ftlog.is_debug():
            ftlog.debug('ActivityWxUserActive._sendActiveReward userId= ',
                        userId, 'rewardKind= ', rewardKind, 'scheduleId= ',
                        scheduleId)
        actInstance = _getActInstance(userId)
        if actInstance:
            userData, expireDay, expireWeek = UserActiveData(userId).loadData()
            if rewardKind == ActiveRewardItem.DAY:
                reward = actInstance.getDayRewardByScheduleId(scheduleId)
                if not reward:
                    raise ActivityWxException(-6, '您没有获得奖励哦~')
                if expireDay:
                    raise ActivityWxException(-7, '您来晚了哦,明天记得早点领取哦~')
                if scheduleId in userData.activeDataDay.scheduleIdList:
                    raise ActivityWxException(-8, '您已领取奖励哦~')
                if userData.activeDataDay.active < reward.active:
                    raise ActivityWxException(-9, '您的日活跃度不够哦~')

                dizhu_util.sendRewardItems(userId, reward.rewards, None,
                                           'ACTIVE_REWARD', 0)
                bireport.reportGameEvent('ACTIVE_REWARDS', userId,
                                         DIZHU_GAMEID, 0, 0, 0, 0, 0, 0,
                                         [scheduleId],
                                         sessiondata.getClientId(userId))
                userData.addDayScheduleId(scheduleId)
                return {
                    'rewards': TYContentItem.encodeList(reward.rewards),
                    'success': 1
                }
            else:
                reward = actInstance.getWeekRewardByScheduleId(scheduleId)
                if not reward:
                    raise ActivityWxException(-6, '您没有获得奖励哦~')

                if expireWeek:
                    raise ActivityWxException(-7, '您来晚了哦,下周记得早点领取哦~')

                if scheduleId in userData.activeDataWeek.scheduleIdList:
                    raise ActivityWxException(-8, '您已领取奖励哦~')
                if userData.activeDataWeek.active < reward.active:
                    raise ActivityWxException(-9, '您的周活跃度不够哦~')

                dizhu_util.sendRewardItems(userId, reward.rewards, None,
                                           'ACTIVE_REWARD', 0)
                userData.addWeekScheduleId(scheduleId)
                bireport.reportGameEvent('ACTIVE_REWARDS', userId,
                                         DIZHU_GAMEID, 0, 0, 0, 0, 0, 0,
                                         [scheduleId],
                                         sessiondata.getClientId(userId))
                return {
                    'rewards': TYContentItem.encodeList(reward.rewards),
                    'success': 1
                }
        raise ActivityWxException(-10, '活动不存在')
Ejemplo n.º 5
0
 def _reloadTasks(self):
     self._taskListMap = {}
     for mixConf in self.room.roomConf.get('mixConf', []):
         mixId = mixConf.get('mixId')
         winStreakTaskList = []
         winStreakTaskConf = mixConf.get('winStreakTask', {})
         for i, reward in enumerate(winStreakTaskConf.get('tasks', [])):
             TYContentItem.decodeFromDict(reward)
             winStreakTaskList.append(WinStreakTask(i, reward))
         self._taskListMap[mixId] = winStreakTaskList
Ejemplo n.º 6
0
    def decodeFromDict(self, d):
        self.unlockSeconds = d.get('unlockSeconds')
        if not isinstance(self.unlockSeconds, int) or self.unlockSeconds < 0:
            raise TYBizConfException(d, 'RewardControlFixedHelp.unlockSeconds must be int')

        self.extraReward = d.get('extraReward')
        if not isinstance(self.extraReward, dict):
            raise TYBizConfException(d, 'RewardControlFixedHelp.extraReward must be dict')
        try:
            TYContentItem.decodeList([self.extraReward])
        except Exception, e:
            raise TYBizConfException(d, 'RewardControlFixedHelp.extraReward Item error=%s' % e.message)
Ejemplo n.º 7
0
    def decodeFromDict(self, d):
        self.id = d.get('id')
        if not isinstance(self.id, int) or self.id < 0:
            raise TYBizConfException(d, 'Bait.id must be int and >0')
        self.name = d.get('name')
        if not isinstance(self.name, (str, unicode)):
            raise TYBizConfException(d, 'Bait.name must be str')
        self.pic = d.get('pic')
        if not isinstance(self.pic, (str, unicode)):
            raise TYBizConfException(d, 'Bait.pic must be str')
        self.chip = d.get('chip')
        if not isinstance(self.chip, int) or self.chip < 0:
            raise TYBizConfException(d, 'Bait.chip must be int and >0')
        self.fish = d.get('fish')
        if not isinstance(self.fish, list):
            raise TYBizConfException(d, 'Bait.id must be int')
        self.superFish = d.get('superFish', 0)
        if not isinstance(self.superFish, int):
            raise TYBizConfException(d, 'Bait.superFish must be int')
        self.couponFishRewards = d.get('couponFishRewards')
        if self.couponFishRewards and not isinstance(self.couponFishRewards,
                                                     list):
            raise TYBizConfException(d, 'Bait.couponFishRewards must be list')
        tempCouponFishRewards = []
        for rewardDict in d.get('couponFishRewards', []):
            itemDict = rewardDict.get('item', {})
            if itemDict:
                tempCouponFishRewards.append({
                    'item':
                    TYContentItem.decodeFromDict(itemDict),
                    'weight':
                    rewardDict.get('weight')
                })
        self.couponFishRewards = tempCouponFishRewards

        self.superFishRewards = d.get('superFishRewards')
        if self.superFishRewards and not isinstance(self.superFishRewards,
                                                    list):
            raise TYBizConfException(d, 'Bait.superFishRewards must be list')
        tempSuperFishRewards = []
        for rewardDict in d.get('superFishRewards', []):
            itemDict = rewardDict.get('item', {})
            if itemDict:
                tempSuperFishRewards.append({
                    'item':
                    TYContentItem.decodeFromDict(itemDict),
                    'weight':
                    rewardDict.get('weight')
                })
        self.superFishRewards = tempSuperFishRewards

        return self
Ejemplo n.º 8
0
def createMatchUser(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.createUserMatchInfo gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId)
    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if userMatchInfo:
        if userMatchInfo.instId == instId:
            if userMatchInfo.state == UserMatchInfo.ST_SIGNIN:
                return ERR_ALREADY_SIGNIN
            return ERR_ALREADY_IN_MATCH
        else:
            ftlog.warn('match_remote.createUserMatchInfo gameId=', gameId,
                       'userId=', userId,
                       'contentItem=', contentItem,
                       'bigRoomId=', bigRoomId,
                       'instId=', instId,
                       'ctrlRoomId=', ctrlRoomId,
                       'recordInstId=', userMatchInfo.instId)

    userMatchInfo = UserMatchInfo(gameId, userId, bigRoomId)
    userMatchInfo.ctrlRoomId = ctrlRoomId
    userMatchInfo.instId = instId
    if contentItem:
        userMatchInfo.feeItem = TYContentItem.decodeFromDict(contentItem)
    saveUserMatchInfo(userMatchInfo)
    return 0
Ejemplo n.º 9
0
def _changeUserBehaviourInfo(userId, ret, behaviourConf):
    try:
        reward = behaviourConf.get('reward') if behaviourConf else None
        if not reward:
            return
        ret['type'] = BEHAVIOUR_TYPE_REWARDED
        daobase.executeUserCmd(userId, 'HSET',
                               'userBehaviour:6:' + str(userId), 'info',
                               strutil.dumps(ret))

        mailStr = behaviourConf.get('mail', '幸运女神的眷顾使你获得了奖励')
        contentItems = TYContentItem.decodeList(reward)
        assetList = dizhu_util.sendRewardItems(userId, contentItems, mailStr,
                                               'USER_BEHAVIOUR_REWARD', userId)
        datachangenotify.sendDataChangeNotify(DIZHU_GAMEID, userId, mailStr)

        # 发奖弹窗
        rewardsList = []
        for assetItemTuple in assetList:
            assetItem = assetItemTuple[0]
            reward = {}
            reward['name'] = assetItem.displayName
            reward['pic'] = assetItem.pic
            reward['count'] = assetItemTuple[1]
            rewardsList.append(reward)

        reward_task = TodoTaskShowRewards(rewardsList)
        TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, reward_task)

        ftlog.info('userBehaviour.sendReward userId=', userId, 'reward=',
                   [(atp[0].kindId, atp[1]) for atp in assetList])

    except Exception, e:
        ftlog.warn('_changeUserBehaviourInfo userId=', userId, 'ret=', ret,
                   'err=', e)
Ejemplo n.º 10
0
def gainUserRanklistReward(userId, rankId, issueNum, clientId=None):
    # 发放周榜奖励
    userData = loadUserData(userId, rankId, issueNum)
    if not userData:
        raise TYBizException(-1, '没有找到用户数据')

    if userData.rewardState == RewardState.ST_NO_REWARD:
        raise TYBizException(-1, '本期没有奖励可领取')

    if userData.rewardState == RewardState.ST_GAIN_REWARD:
        raise TYBizException(-1, '已经领取了奖励')

    clientId = clientId or sessiondata.getClientId(userId)
    rankRewards = findRankRewardsByRank(rankId, issueNum, clientId,
                                        userData.rank)
    if not rankRewards:
        if ftlog.is_debug():
            ftlog.debug('gainUserRanklistReward rankReward is None. userId=',
                        userId, 'rankId=', rankId, 'issueNum=', issueNum,
                        'clientId=', clientId)
        # TODO warn or error
        raise TYBizException(-1, '未取到对应奖励配置')

    userData.rewardState = RewardState.ST_GAIN_REWARD
    saveUserData(userData)

    contentItems = TYContentItem.decodeList(rankRewards.get('items'))
    assetList = dizhu_util.sendRewardItems(userId, contentItems,
                                           _scoreRankConf.rewardMail,
                                           'DIZHU_SCORE_RANKLIST', int(rankId))

    ftlog.info('gainUserRanklistReward', 'userId=', userId, 'rankId=', rankId,
               'issueNum=', issueNum, 'rank=', userData.rank, 'rewards=',
               [(atp[0].kindId, atp[1]) for atp in assetList])
    return assetList
Ejemplo n.º 11
0
    def sendAssetsListToUser(cls,
                             gameId,
                             userId,
                             assetList,
                             eventId,
                             mail=None,
                             intEventParam=0):
        '''
        :param gameId 统计用途,地主就写6
        :param assetList 要发送的资产, 格式必须是:[{itemId:'item:0011', count:1}, ...]
        :param eventId 事件ID,要在config/poker/map.bieventid.json中注册
        :param mail(optional) 给用户邮箱发送信息,默认不发送
        '''
        timestamp = pktimestamp.getCurrentTimestamp()
        itemList = []
        for i in xrange(0, len(assetList)):
            itemList.insert(i, TYContentItem.decodeFromDict(assetList[i]))
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetList = userAssets.sendContentItemList(gameId, itemList, 1, True,
                                                   timestamp, eventId,
                                                   intEventParam)

        # 通知用户道具和消息存在改变
        if assetList:
            datachangenotify.sendDataChangeNotify(
                gameId, userId, TYAssetUtils.getChangeDataNames(assetList))

        # 发送邮箱信息
        if mail and len(mail) > 0:
            pkmessage.sendPrivate(9999, userId, 0, mail)
Ejemplo n.º 12
0
    def sendAssetsToUser(cls,
                         gameId,
                         userId,
                         assets,
                         eventId,
                         mail=None,
                         intEventParam=0):
        '''
        :param gameId 统计用途,地主就写6
        :param assets 要发送的资产, 格式必须是:{itemId:'item:0011', count:1}
        :param eventId 事件ID,要在config/poker/map.bieventid.json中注册
        :param mail(optional) 给用户邮箱发送信息,默认不发送
        '''
        timestamp = pktimestamp.getCurrentTimestamp()
        contentitem = TYContentItem.decodeFromDict(assets)
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetKind, consumecount, finalcount = userAssets.addAsset(
            gameId, contentitem.assetKindId, contentitem.count, timestamp,
            eventId, intEventParam)
        # 通知用户道具和消息存在改变
        if assetKind.keyForChangeNotify:
            datachangenotify.sendDataChangeNotify(
                gameId, userId, [assetKind.keyForChangeNotify, 'message'])

        # 发送邮箱信息
        if mail and len(mail) > 0:
            pkmessage.sendPrivate(9999, userId, 0, mail)

        return (assetKind, consumecount, finalcount)
Ejemplo n.º 13
0
def sendGiftsToUser(userId, gameId, clientId, items):
    '''
        多个奖品时的发奖,或者一个奖品的发奖,items为数组
    '''
    contentItemList = []
    rouletteMap = getRouletteMap()

    for item in items:
        itemMap = rouletteMap.get(item, {})
        if itemMap:
            # 添加判断流程,判断奖励是否需要发送led
            if itemMap.get('isSendLed', False):
                userInfo = halluser.getUserInfo(userId, gameId, clientId)
                msgstr = '恭喜' + userInfo.get(
                    'name', '') + '玩家在幸运大转盘中,抽中了' + itemMap.get(
                        'itemDesc', '') + '大奖!快来参与,大奖得主就是你!'
                hallled.sendLed(HALL_GAMEID, msgstr, 1, 'hall')

            # 添加中奖内容
            contentItemList.append(
                TYContentItem.decodeFromDict({
                    'itemId': itemMap.get('itemId'),
                    'count': itemMap.get('count')
                }))

    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    results = userAssets.sendContentItemList(gameId, contentItemList, 1, True,
                                             int(time.time()), 'ROULETTE_GOLD',
                                             0)
    datachangenotify.sendDataChangeNotify(
        gameId, userId, TYAssetUtils.getChangeDataNames(results))
Ejemplo n.º 14
0
    def unmarshal(self, d):
        assets = d.get(
            'assets')  # 格式必须是:[{'itemId':'item:0011', 'count':1}, ...]
        if not isinstance(assets, list):
            raise Exception(
                "AttachmentAsset.unmarshal assets wrong:{}".format(assets))
        self._itemlist = []
        for kind_2_cnt in assets:
            d_item = {
                'itemId': kind_2_cnt['itemId'],
                'count': int(kind_2_cnt['count'])
            }
            self._itemlist.append(TYContentItem.decodeFromDict(d_item))

        self._eventid = d.get('eventid')
        if not isstring(self._eventid):
            raise Exception(
                "AttachmentAsset.unmarshal eventid wrong:{}".format(
                    self._eventid))

        self._eventparam = d.get('eventparam')
        if not isinstance(self._eventparam, int):
            raise Exception(
                "AttachmentAsset.unmarshal eventparam wrong:{}".format(
                    self._eventparam))
Ejemplo n.º 15
0
    def handleRequest(self, userId, clientId, action, msg):
        if action == self.ACTION_SHARE_CHARM_RANK_LIST:
            return self.getRankRewardList(userId)
        elif action == self.ACTION_SHARE_CHARM_REWARD:
            # 更改用户领奖状态
            issue = calculateLastIssue(self.settleDayOrWeek)
            realRank = getUserRealRank(userId, self.actId, issue)
            rankRewardItem = self.getUserRankRewardItem(userId, realRank)
            userData = UserShareCharmData(userId).loadUserData(self.actId)
            issueData = userData.getIssueData(issue)

            if not issueData:
                raise ActivityWxException(-6, '您没有参与%s活动哦~' % issue)

            if issueData.state == SHARE_CHARM_REWARD_STATE_GOT:
                raise ActivityWxException(-4, '您已领取奖励哦~')
            # 发奖
            if rankRewardItem:
                userData.updateState(self.actId, issue)
                rewards = rankRewardItem.rewards
                rewardsItems = TYContentItem.decodeList(rewards)
                dizhu_util.sendRewardItems(userId, rewardsItems, '',
                                           'ACT_WX_SHARE_CHARM', self.intActId)
                for reward in rewards:
                    if reward['itemId'] == 'user:coupon':
                        from hall.game import TGHall
                        TGHall.getEventBus().publishEvent(
                            UserCouponReceiveEvent(
                                HALL_GAMEID, userId, reward['count'],
                                user_coupon_details.USER_COUPON_SHARE_CHARM))
                return rewards
            raise ActivityWxException(-5, '您没有奖励可领取哦~')
        return None
def chooseReward(self, userId, matchId, rank):
    if ftlog.is_debug():
        ftlog.debug('MatchLottery userId=', userId, 'matchId=', matchId,
                    'rank=', rank)

    if not self.matchList:
        d = dizhuconf.getMatchLotteryConf()
        self.decodeFromDict(d)

    if not self.checkMatchRank(userId, matchId):
        ftlog.warn('MatchLottery.checkMatchRank failed. userId=', userId,
                   'matchId=', matchId, 'rank=', rank)
        return None, None

    items = self.getMatchLotteryConf(matchId, rank)
    if not items:
        ftlog.warn('MatchLottery.checkMatchRank failed. no items. userId=',
                   userId, 'matchId=', matchId, 'rank=', rank)
        return None, None

    weights = 0
    for item in items:
        weights += item.get('weight', 0)
    r = random.randint(0, weights)
    lotteryReward = []
    weightTotal = 0
    for item in items:
        weightTotal += item.get('weight', 0)
        if r <= weightTotal:
            lotteryReward.append({
                'itemId': str(item.get('itemId')),
                'count': item.get('count')
            })
            break
    lotteryReward = items[-1] if not lotteryReward else lotteryReward

    if ftlog.is_debug():
        ftlog.debug('MatchLottery weights=', weights, 'r=', r, 'userId=',
                    userId, 'lotteryReward=', lotteryReward)

    if lotteryReward:
        contentItems = TYContentItem.decodeList(lotteryReward)
        assetList = dizhu_util.sendRewardItems(userId, contentItems, '',
                                               'DIZHU_MATCH_LOTTERY', 0)

        ftlog.info('MatchLottery.chooseReward userId=', userId, 'matchId=',
                   matchId, 'lotteryReward=', lotteryReward, 'assetList=',
                   assetList)

    for i in items:
        assetKind = hallitem.itemSystem.findAssetKind(i['itemId'])
        i['img'] = assetKind.pic
        i['des'] = assetKind.desc
        i['name'] = assetKind.displayName

    if ftlog.is_debug():
        ftlog.debug('MatchLottery.chooseReward userId=', userId, 'matchId=',
                    matchId, 'rank=', rank, 'lotteryReward=', lotteryReward)

    return lotteryReward, items
Ejemplo n.º 17
0
    def getDay30Reward(self, gameId, userId, clientId):
        from dizhu.activities.login30_360 import Login30
        status = 0
        all_count = 0
        get_count = 0
        tip = ''
        ecode = 0
        try:
            conf = dizhuconf.getActivityConf("huiyuan_360")
            data = gamedata.getGameAttrJson(userId, gameId, Login30.attr_act,
                                            {})
            if data:
                if data["get_count"] != data["current_count"]:
                    reward = conf.get("login30", [])[data["current_count"] - 1]
                    contentItem = TYContentItem.decodeFromDict(reward)
                    tip = self.sendReward(gameId, userId, clientId,
                                          contentItem, 'HUI_YUAN_360', 0)
                    data["get_count"] = data["current_count"]

                all_count = data["all_count"]
                get_count = data["get_count"]

                status = int(data["get_count"] < data["current_count"])

                gamedata.setGameAttr(userId, gameId, Login30.attr_act,
                                     json.dumps(data))
        except:
            ftlog.exception()
            tip = "领取失败"
            ecode = 1

        return tip, ecode, status, all_count, get_count
Ejemplo n.º 18
0
def signoutMatch(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug("match_remote.signoutMatch gameId=", gameId, "userId=",
                    userId, "contentItem=", contentItem, "bigRoomId=",
                    bigRoomId, "instId=", instId, "ctrlRoomId=", ctrlRoomId)
    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if not userMatchInfo:
        return 0, None

    if userMatchInfo.instId != instId:
        ftlog.debug("match_remote.signoutMatch diffInstId gameId=", gameId,
                    "userId=", userId, "contentItem=", contentItem,
                    "bigRoomId=", bigRoomId, "instId=", instId, "ctrlRoomId=",
                    ctrlRoomId, "recordInstId=", userMatchInfo.instId)
        return 0, None

    if userMatchInfo.state != UserMatchInfo.ST_SIGNIN:
        return ERR_ALREADY_IN_MATCH, None

    removeUserMatchInfo(userMatchInfo)
    daobase.executeTableCmd(ctrlRoomId, 0, "srem", "signs:" + str(ctrlRoomId),
                            userId)
    ftlog.debug("match_remote.signoutMatch gameId=", gameId, "userId=", userId,
                "contentItem=", contentItem, "bigRoomId=", bigRoomId,
                "instId=", instId, "ctrlRoomId=", ctrlRoomId)
    if userId > 10000 and contentItem:
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        item = TYContentItem.decodeFromDict(contentItem)
        assetList = userAssets.sendContentItemList(
            gameId, [item], 1, True, pktimestamp.getCurrentTimestamp(),
            "MATCH_RETURN_FEE", bigRoomId)
        datachangenotify.sendDataChangeNotify(
            gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
    return 0, None
Ejemplo n.º 19
0
def createMatchUser(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.createUserMatchInfo gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId)
    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if userMatchInfo:
        if userMatchInfo.instId == instId:
            if userMatchInfo.state == UserMatchInfo.ST_SIGNIN:
                return ERR_ALREADY_SIGNIN
            return ERR_ALREADY_IN_MATCH
        else:
            ftlog.warn('match_remote.createUserMatchInfo gameId=', gameId,
                       'userId=', userId,
                       'contentItem=', contentItem,
                       'bigRoomId=', bigRoomId,
                       'instId=', instId,
                       'ctrlRoomId=', ctrlRoomId,
                       'recordInstId=', userMatchInfo.instId)
            
    userMatchInfo = UserMatchInfo(gameId, userId, bigRoomId)
    userMatchInfo.ctrlRoomId = ctrlRoomId
    userMatchInfo.instId = instId
    if contentItem:
        userMatchInfo.feeItem = TYContentItem.decodeFromDict(contentItem)
    saveUserMatchInfo(userMatchInfo)
    return 0
Ejemplo n.º 20
0
    def _initial(self):
        _exchanges = {}
        for info in self._clientConf['config']['exchange']:
            info2 = copy.copy(info)
            info2['content'] = TYContentRegister.decodeFromDict(info['content'])
            costs = []
            for costdict in info2['costs']:
                costs.append(TYContentItem.decodeFromDict(costdict))
            if not costs:
                raise TYBizConfException(info, 'costs is empty!!!')
            info2['costs'] = costs
            _exchanges[info2['id']] = info2

            # 原始配置填充图片信息
            content_items = info2['content'].getItems()
            assetKind = hallitem.itemSystem.findAssetKind(content_items[0].assetKindId)
            info['pic'] = assetKind.pic
        # 原始配置,还需要一个消耗物品的图片
        for info in _exchanges.itervalues():
            for cost in info['costs']:
                self.costAssetKindId = cost.assetKindId
                assetKind = hallitem.itemSystem.findAssetKind(cost.assetKindId)
                self._clientConf['config']['costAssetPic'] = assetKind.pic
                break
        self._exchanges = _exchanges
Ejemplo n.º 21
0
    def getChouJiangReward(self, gameId, userId, clientId):
        from dizhu.activities.choujiang_360 import ChouJiang360
        status = 0
        all_count = 0
        get_count = 0
        tip = ''
        ecode = 0
        try:
            data = gamedata.getGameAttrJson(userId, gameId,
                                            ChouJiang360.attr_act, {})
            if data:
                if data["get_count"] < data["current_count"]:
                    tip = self.sendReward(gameId, userId, clientId,
                                          TYContentItem('item:4147', 1),
                                          'HUI_YUAN_360', 0)
                    tip = ''.join([tip, ' 请去背包查收'])
                    data["get_count"] += 1

                all_count = data["all_count"]
                get_count = data["get_count"]

                status = int(data["get_count"] < data["current_count"])

                gamedata.setGameAttr(userId, gameId, ChouJiang360.attr_act,
                                     json.dumps(data))
        except:
            ftlog.exception()
            tip = "领取失败"
            ecode = 1

        return tip, ecode, status, all_count, get_count
Ejemplo n.º 22
0
def sendLoginReward(gameId, userId, clientId, iscreate, isdayfirst):
    if iscreate:
        newUserReward = configure.getGameJson(gameId, 'login.reward',
                                              {}).get('newUserReward')
        if newUserReward:
            if not newUserReward.get('open', 0):
                return
            rewards = newUserReward.get('rewards')
            if rewards:
                mail = newUserReward.get('mail')
                contentItems = TYContentItem.decodeList(rewards)
                dizhu_util.sendRewardItems(userId, contentItems, mail,
                                           'LOGIN_REWARD', 0)
                FTTasklet.getCurrentFTTasklet().sleepNb(1.5)
                msg = MsgPack()
                msg.setCmd('dizhu')
                msg.setResult('action', 'new_user_reward')
                msg.setResult('rewards', rewards)
                msg.setResult('cardNoteCount',
                              newUserReward.get('cardNoteCount', 0))
                router.sendToUser(msg, userId)
                ftlog.info(
                    'dizhu_login_reward.sendLoginReward newUserReward userId=',
                    userId, 'gameId=', gameId, 'clientId=', clientId,
                    'iscreate=', iscreate, 'isdayfirst=', isdayfirst,
                    'rewards=', rewards)
Ejemplo n.º 23
0
    def decodeFromDict(self, d):
        self.startCount = d.get('startCount')
        if not isinstance(self.startCount, int):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.startCount must be int')

        self.endCount = d.get('endCount')
        if not isinstance(self.endCount, int):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.endCount must be int')

        self.rewardDesc = d.get('rewardDesc')
        if not isstring(self.rewardDesc):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.rewardDesc must be str')

        self.rewardPic = d.get('rewardPic')
        if not isstring(self.rewardPic):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.rewardPic must be str')

        rewards = d.get('rewards')
        if not isinstance(rewards, list):
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.rewards must be list')
        try:
            self.rewards = TYContentItem.decodeList(rewards)
            self.rewardsConf = rewards
        except Exception, e:
            raise TYBizConfException(d, 'WXFollowConf.RewardItem.rewards err=%s' % e.message)
Ejemplo n.º 24
0
    def decodeFromDict(self, d):
        self.active = d.get('active')
        if not isinstance(self.active, int):
            raise TYBizConfException(d, 'ActiveRewardItem.active must be int')

        self.scheduleId = d.get('scheduleId')
        if not isinstance(self.scheduleId, int):
            raise TYBizConfException(
                d, 'ActiveRewardItem.scheduleId must be int')

        self.rewardDesc = d.get('rewardDesc')
        if not isstring(self.rewardDesc):
            raise TYBizConfException(
                d, 'ActiveRewardItem.rewardDesc must be str')
        self.rewardPic = d.get('rewardPic')
        if not isstring(self.rewardPic):
            raise TYBizConfException(d,
                                     'ActiveRewardItem.rewardPic must be str')
        rewards = d.get('rewards')
        if not isinstance(rewards, list):
            raise TYBizConfException(d,
                                     'ActiveRewardItem.rewards must be list')
        try:
            r = TYContentItem.decodeList(rewards)
        except Exception, e:
            raise TYBizConfException(
                d, 'ActiveRewardItem.rewards err=%s' % e.message)
Ejemplo n.º 25
0
 def _toDictImpl(self, d):
     d['signinCount'] = self.signinCount
     d['startType'] = self.startType
     d['instId'] = self.instId
     d['startTime'] = self.startTime
     d['signinTime'] = self.signinTime
     if self.fees:
         d['fees'] = TYContentItem.encodeList(self.fees)
Ejemplo n.º 26
0
 def loadStatus(self, userId):
     try:
         itemMap = {}
         paddingList = []
         d = pkgamedata.getGameAttrJson(userId, 6, 'flipcard')
         if d:
             flipTime = int(d['ut'])
             items = d.get('items', [])
             for item in items:
                 itemMap[item['idx']] = TYContentItem(item['assetId'], item['count'])
             paddings = d.get('paddings', [])
             for item in paddings:
                 paddingList.append(TYContentItem(item['assetId'], item['count']))
             return DizhuFlipCardStatus(flipTime, itemMap, paddingList) 
     except:
         ftlog.error()
     return None
Ejemplo n.º 27
0
 def _toDictImpl(self, d):
     d['signinCount'] = self.signinCount
     d['startType'] = self.startType
     d['instId'] = self.instId
     d['startTime'] = self.startTime
     d['signinTime'] = self.signinTime
     if self.fees:
         d['fees'] = TYContentItem.encodeList(self.fees)
Ejemplo n.º 28
0
 def decodeRecord(cls, userId, jstr):
     d = strutil.loads(jstr)
     record = SigninRecord(userId)
     record.signinTime = d['st']
     fee = d.get('fee')
     if fee:
         record.fee = TYContentItem.decodeFromDict(fee)
     return record
Ejemplo n.º 29
0
    def processEnterGame(cls, evt):
        # # 检查当前已结束赛季并发放赛季奖励, 只发放上一期的
        if ftlog.is_debug():
            ftlog.debug('============= processEnterGame userId=', evt.userId)
        _, intClientId = sessiondata.getClientIdNum(evt.userId)
        if intClientId == 24105:
            latestTwoIssues = SegmentMatchHelper.getIssueStateList()[-2:]
            for issuestate in reversed(latestTwoIssues):
                if issuestate['state'] == 0:
                    continue

                # 判断用户有没有结算此赛季
                userData = SegmentMatchHelper.getUserSegmentDataIssue(
                    evt.userId, issuestate['issue']) or UserSegmentDataIssue()
                if userData and userData.segmentRewardsState == UserSegmentDataIssue.IDEAL:
                    # 结算 发奖
                    settlementRanking(evt.userId, issuestate['issue'])

        segmentConf = getSegmentConf()
        if segmentConf.closed:
            return

        if evt.dayFirst:
            # 检查用户是否已经发送
            if not gamedata.getGameAttrInt(evt.userId, DIZHU_GAMEID,
                                           'wxNotice'):
                # 保存消息记录
                gamedata.setGameAttr(evt.userId, DIZHU_GAMEID, 'wxNotice', 1)

                # 新用户发送一条额外消息
                mailstr = '游戏公告#如有任何意见建议,欢迎加客服微信:Tuyoo_taozi,进入官方群反馈'
                message.send(DIZHU_GAMEID, message.MESSAGE_TYPE_SYSTEM,
                             evt.userId, mailstr)

        # 同步钻石为用户道具
        if not segmentdata.getSegmentAttr(evt.userId, DIZHU_GAMEID,
                                          'diamondConvert'):
            segmentdata.setSegmentAttr(evt.userId, DIZHU_GAMEID,
                                       'diamondConvert', 1)
            userDiamond = userdata.getAttr(evt.userId, 'diamond')
            if userDiamond:
                # count
                user_remote.consumeAssets(DIZHU_GAMEID, evt.userId,
                                          [{
                                              'itemId': 'user:diamond',
                                              'count': userDiamond
                                          }], 'DIZHU_SEGMENT_DIAMOND_CONVERT',
                                          0)
                contentItems = TYContentItem.decodeList([{
                    'itemId': 'item:1311',
                    'count': userDiamond
                }])
                from dizhu.entity import dizhu_util
                dizhu_util.sendRewardItems(evt.userId, contentItems, None,
                                           'DIZHU_SEGMENT_DIAMOND_CONVERT', 0)
                ftlog.info('DizhuSegmentRewardsHelper diamondConvert userId=',
                           evt.userId, 'userDiamond=', userDiamond)
Ejemplo n.º 30
0
 def fromDict(self, d):
     self.signinCount = d.get('signinCount', 0)
     self.startType = d.get('startType')
     self.instId = d.get('instId')
     self.startTime = d.get('startTime')
     self.signinTime = d.get('signinTime')
     fees = d.get('fees')
     if fees:
         self.fees = TYContentItem.decodeList(fees)
     return self
Ejemplo n.º 31
0
 def fromDict(self, d):
     self.signinCount = d.get('signinCount', 0)
     self.startType = d.get('startType')
     self.instId = d.get('instId')
     self.startTime = d.get('startTime')
     self.signinTime = d.get('signinTime')
     fees = d.get('fees')
     if fees:
         self.fees = TYContentItem.decodeList(fees)
     return self
Ejemplo n.º 32
0
 def decodeFromDict(self, d):
     self.prizeDetail = d.get('prizeDetail', '')
     if not isstring(self.prizeDetail):
         raise TYBizConfException(
             d, 'NeituiguangConf.prizeDetail must be string')
     self.prizeImgUrl = d.get('prizeImgUrl', '')
     if not isstring(self.prizeImgUrl):
         raise TYBizConfException(
             d, 'NeituiguangConf.prizeImgUrl must be string')
     self.prizeRewardDesc = d.get('prizeRewardDesc', '')
     if not isstring(self.prizeRewardDesc):
         raise TYBizConfException(
             d, 'NeituiguangConf.prizeRewardDesc must be string')
     self.prizeNotGotRewardDesc = d.get('prizeNotGotRewardDesc', '')
     if not isstring(self.prizeNotGotRewardDesc):
         raise TYBizConfException(
             d, 'NeituiguangConf.prizeNotGotRewardDesc must be string')
     self.prizeGotTotalRewardDesc = d.get('prizeGotTotalRewardDesc', '')
     if not isstring(self.prizeGotTotalRewardDesc):
         raise TYBizConfException(
             d, 'NeituiguangConf.prizeGotTotalRewardDesc must be string')
     self.prizeAvailableRewardDesc = d.get('prizeAvailableRewardDesc', '')
     if not isstring(self.prizeAvailableRewardDesc):
         raise TYBizConfException(
             d, 'NeituiguangConf.prizeAvailableRewardDesc must be string')
     self.prizeRewardTips = d.get('prizeRewardTips', '')
     if not isstring(self.prizeRewardTips):
         raise TYBizConfException(
             d, 'NeituiguangConf.prizeRewardTips must be string')
     prizeRewardItem = d.get('prizeRewardItem', {})
     if not isinstance(prizeRewardItem, dict):
         raise TYBizConfException(
             d, 'NeituiguangConf.prizeRewardItem must be dict')
     if prizeRewardItem:
         self.prizeRewardItem = TYContentItem.decodeFromDict(
             prizeRewardItem)
     self.shareLoc = d.get('shareLoc', '')
     if not isstring(self.shareLoc):
         raise TYBizConfException(
             d, 'NeituiguangConf.shareLoc must be string')
     self.taskDetail = d.get('taskDetail', '')
     if not isstring(self.taskDetail):
         raise TYBizConfException(
             d, 'NeituiguangConf.taskDetail must be string')
     self.pleaseBindPhone = d.get('pleaseBindPhone', '')
     if not isstring(self.pleaseBindPhone):
         raise TYBizConfException(
             d, 'NeituiguangConf.pleaseBindPhone must be string')
     self.defaultShareId = d.get('defaultShareId')
     if self.defaultShareId is not None and not isinstance(
             self.defaultShareId, int):
         raise TYBizConfException(
             d, 'NeituiguangConf.defaultShareId must be int')
     return self
Ejemplo n.º 33
0
def decodeUserMatchInfo(gameId, userId, bigRoomId, jstr):
    d = strutil.loads(jstr)
    if d:
        ret = UserMatchInfo(gameId, userId, bigRoomId)
        ret.state = d["st"]
        ret.instId = d["instId"]
        ret.ctrlRoomId = d["crid"]
        fee = d.get("fee")
        if fee:
            ret.feeItem = TYContentItem.decodeFromDict(fee)
        return ret
Ejemplo n.º 34
0
def decodeUserMatchInfo(gameId, userId, bigRoomId, jstr):
    d = strutil.loads(jstr)
    if d:
        ret = UserMatchInfo(gameId, userId, bigRoomId)
        ret.state = d['st']
        ret.instId = d['instId']
        ret.ctrlRoomId = d['crid']
        fee = d.get('fee')
        if fee:
            ret.feeItem = TYContentItem.decodeFromDict(fee)
        return ret
    return None
Ejemplo n.º 35
0
def signinMatch(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.signinMatch gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId)
    try:
        userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
        if userMatchInfo:
            if userMatchInfo.instId == instId:
                if userMatchInfo.state == UserMatchInfo.ST_SIGNIN:
                    return ERR_ALREADY_SIGNIN, None
                return ERR_ALREADY_IN_MATCH, None
            else:
                ftlog.warn('match_remote.signinMatch gameId=', gameId,
                           'userId=', userId,
                           'contentItem=', contentItem,
                           'bigRoomId=', bigRoomId,
                           'instId=', instId,
                           'ctrlRoomId=', ctrlRoomId,
                           'recordInstId=', userMatchInfo.instId)

        userMatchInfo = UserMatchInfo(gameId, userId, bigRoomId)
        userMatchInfo.ctrlRoomId = ctrlRoomId
        userMatchInfo.instId = instId
        if contentItem:
            userMatchInfo.feeItem = TYContentItem.decodeFromDict(contentItem)
        if userId > 10000 and contentItem:
            userAssets = hallitem.itemSystem.loadUserAssets(userId)
            assetTuple = userAssets.consumeAsset(gameId,
                                                 contentItem['itemId'],
                                                 contentItem['count'],
                                                 pktimestamp.getCurrentTimestamp(),
                                                 'MATCH_SIGNIN_FEE', bigRoomId)
            if assetTuple[1] < contentItem['count']:
                raise TYAssetNotEnoughException(assetTuple[0], contentItem['count'], assetTuple[2])
            # 记录用户
            datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames([assetTuple]))
        saveUserMatchInfo(userMatchInfo)
        daobase.executeTableCmd(ctrlRoomId, 0, 'sadd', 'signs:' + str(ctrlRoomId), userId)
        return 0, None
    except TYAssetNotEnoughException, e:
        return ERR_FEE_NOT_ENOUGH, (e.assetKind.kindId, e.required - e.actually)
Ejemplo n.º 36
0
def signoutMatch(gameId, userId, contentItem, bigRoomId, instId, ctrlRoomId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.signoutMatch gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId)
    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if not userMatchInfo:
        return 0, None

    if userMatchInfo.instId != instId:
        ftlog.debug('match_remote.signoutMatch diffInstId gameId=', gameId,
                    'userId=', userId,
                    'contentItem=', contentItem,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId,
                    'recordInstId=', userMatchInfo.instId)
        return 0, None

    if userMatchInfo.state != UserMatchInfo.ST_SIGNIN:
        return ERR_ALREADY_IN_MATCH, None

    removeUserMatchInfo(userMatchInfo)
    daobase.executeTableCmd(ctrlRoomId, 0, 'srem', 'signs:' + str(ctrlRoomId), userId)
    ftlog.debug('match_remote.signoutMatch gameId=', gameId,
                'userId=', userId,
                'contentItem=', contentItem,
                'bigRoomId=', bigRoomId,
                'instId=', instId,
                'ctrlRoomId=', ctrlRoomId)
    if userId > 10000 and contentItem:
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        item = TYContentItem.decodeFromDict(contentItem)
        assetList = userAssets.sendContentItemList(gameId, [item], 1, True,
                                                   pktimestamp.getCurrentTimestamp(),
                                                   'MATCH_RETURN_FEE', bigRoomId)
        datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
    return 0, None
Ejemplo n.º 37
0
 def decodeFromDict(self, d):
     self.prizeDetail = d.get('prizeDetail', '')
     if not isstring(self.prizeDetail):
         raise TYBizConfException(d, 'NeituiguangConf.prizeDetail must be string')
     self.prizeImgUrl = d.get('prizeImgUrl', '')
     if not isstring(self.prizeImgUrl):
         raise TYBizConfException(d, 'NeituiguangConf.prizeImgUrl must be string')
     self.prizeRewardDesc = d.get('prizeRewardDesc', '')
     if not isstring(self.prizeRewardDesc):
         raise TYBizConfException(d, 'NeituiguangConf.prizeRewardDesc must be string')
     self.prizeNotGotRewardDesc = d.get('prizeNotGotRewardDesc', '')
     if not isstring(self.prizeNotGotRewardDesc):
         raise TYBizConfException(d, 'NeituiguangConf.prizeNotGotRewardDesc must be string')
     self.prizeGotTotalRewardDesc = d.get('prizeGotTotalRewardDesc', '')
     if not isstring(self.prizeGotTotalRewardDesc):
         raise TYBizConfException(d, 'NeituiguangConf.prizeGotTotalRewardDesc must be string')
     self.prizeAvailableRewardDesc = d.get('prizeAvailableRewardDesc', '')
     if not isstring(self.prizeAvailableRewardDesc):
         raise TYBizConfException(d, 'NeituiguangConf.prizeAvailableRewardDesc must be string')
     self.prizeRewardTips = d.get('prizeRewardTips', '')
     if not isstring(self.prizeRewardTips):
         raise TYBizConfException(d, 'NeituiguangConf.prizeRewardTips must be string')
     prizeRewardItem = d.get('prizeRewardItem', {})
     if not isinstance(prizeRewardItem, dict):
         raise TYBizConfException(d, 'NeituiguangConf.prizeRewardItem must be dict')
     if prizeRewardItem:
         self.prizeRewardItem = TYContentItem.decodeFromDict(prizeRewardItem)
     self.shareLoc = d.get('shareLoc', '')
     if not isstring(self.shareLoc):
         raise TYBizConfException(d, 'NeituiguangConf.shareLoc must be string')
     self.taskDetail = d.get('taskDetail', '')
     if not isstring(self.taskDetail):
         raise TYBizConfException(d, 'NeituiguangConf.taskDetail must be string')
     self.pleaseBindPhone = d.get('pleaseBindPhone', '')
     if not isstring(self.pleaseBindPhone):
         raise TYBizConfException(d, 'NeituiguangConf.pleaseBindPhone must be string')
     self.defaultShareId = d.get('defaultShareId')
     if self.defaultShareId is not None and not isinstance(self.defaultShareId, int):
         raise TYBizConfException(d, 'NeituiguangConf.defaultShareId must be int')
     return self
Ejemplo n.º 38
0
def sendGiftsToUser(userId, gameId, clientId, items):
    '''
        多个奖品时的发奖,或者一个奖品的发奖,items为数组
    '''
    contentItemList = []
    rouletteMap = getRouletteMap()

    for item in items:
        itemMap = rouletteMap.get(item, {})
        if itemMap:
            # 添加判断流程,判断奖励是否需要发送led
            if itemMap.get('isSendLed', False):
                userInfo = halluser.getUserInfo(userId, gameId, clientId)
                msgstr = '恭喜' + userInfo.get('name', '') + '玩家在幸运大转盘中,抽中了' + itemMap.get('itemDesc',
                                                                                         '') + '大奖!快来参与,大奖得主就是你!'
                hallled.sendLed(HALL_GAMEID, msgstr, 1, 'hall')

            # 添加中奖内容    
            contentItemList.append(
                TYContentItem.decodeFromDict({'itemId': itemMap.get('itemId'), 'count': itemMap.get('count')}))

    userAssets = hallitem.itemSystem.loadUserAssets(userId)
    results = userAssets.sendContentItemList(gameId, contentItemList, 1, True, int(time.time()), 'ROULETTE_GOLD', 0)
    datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(results))
Ejemplo n.º 39
0
    def decodeFromDict(self, d):
        inviteRewardItem = d.get('inviteRewardItem', {})
        if not isinstance(inviteRewardItem, dict):
            raise TYBizConfException(d, 'InviteConf.inviteRewardItem must be dict')
        if inviteRewardItem:
            self.inviteRewardItem = TYContentItem.decodeFromDict(inviteRewardItem)

        self.gotoTitle = d.get('gotoTitle', '')
        if not isstring(self.gotoTitle):
            raise TYBizConfException(d, 'InviteConf.gotoTitle must be string')

        self.gotoDesc = ''
        if not isstring(self.gotoDesc):
            raise TYBizConfException(d, 'InviteConf.gotoDesc must be string')

        self.gotoUrl = d.get('gotoUrl', '')
        if not isstring(self.gotoUrl):
            raise TYBizConfException(d, 'InviteConf.gotoUrl must be string')

        self.inviteTitle = d.get('inviteTitle', '')
        if not isstring(self.inviteTitle):
            raise TYBizConfException(d, 'InviteConf.inviteTitle must be string')

        self.inviteDesc = d.get('inviteDesc', '')
        if not isstring(self.inviteDesc):
            raise TYBizConfException(d, 'InviteConf.inviteDesc must be string')

        self.inviteUrl = d.get('inviteUrl', '')
        if not isstring(self.inviteUrl):
            raise TYBizConfException(d, 'InviteConf.inviteUrl must be string')

        self.name = d.get('name', '')
        if not isstring(self.name):
            raise TYBizConfException(d, 'InviteConf.name must be string')

        return self
Ejemplo n.º 40
0
def unlockUserForMatch(gameId, userId, bigRoomId, instId, ctrlRoomId, tableId, seatId, contentItem):
    if ftlog.is_debug():
        ftlog.debug('match_remote.unlockUserForMatch gameId=', gameId,
                    'userId=', userId,
                    'bigRoomId=', bigRoomId,
                    'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId,
                    'tableId=', tableId,
                    'seatId=', seatId,
                    'contentItem=', contentItem)

    userMatchInfo = loadUserMatchInfo(gameId, userId, bigRoomId)
    if userMatchInfo:
        # 此处有异常,正常要有userMatchInfo
        removeUserMatchInfo(userMatchInfo)

        if contentItem:
            try:
                contentItemObj = TYContentItem.decodeFromDict(contentItem)
                userAssets = hallitem.itemSystem.loadUserAssets(userId)
                assetList = userAssets.sendContentItemList(gameId, [contentItemObj],
                                                           1, True,
                                                           pktimestamp.getCurrentTimestamp(),
                                                           'MATCH_RETURN_FEE', bigRoomId)
                datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames(assetList))
                ftlog.info('match_remote.unlockUserForMatch returnFees ok gameId=', gameId,
                           'userId=', userId,
                           'bigRoomId=', bigRoomId,
                           'instId=', instId,
                           'ctrlRoomId=', ctrlRoomId,
                           'tableId=', tableId,
                           'seatId=', seatId,
                           'contentItem=', contentItem)
            except:
                ftlog.error('match_remote.unlockUserForMatch gameId=', gameId,
                            'userId=', userId,
                            'bigRoomId=', bigRoomId,
                            'instId=', instId,
                            'ctrlRoomId=', ctrlRoomId,
                            'tableId=', tableId,
                            'seatId=', seatId,
                            'contentItem=', contentItem)
        try:
            onlinedata.removeOnlineLoc(userId, ctrlRoomId, tableId)
        except:
            ftlog.error('match_remote.unlockUserForMatch gameId=', gameId,
                        'userId=', userId,
                        'bigRoomId=', bigRoomId,
                        'instId=', instId,
                        'ctrlRoomId=', ctrlRoomId,
                        'tableId=', tableId,
                        'seatId=', seatId,
                        'contentItem=', contentItem)

        ftlog.info('match_remote.unlockUserForMatch ok gameId=', gameId,
                   'userId=', userId,
                   'bigRoomId=', bigRoomId,
                   'instId=', instId,
                   'ctrlRoomId=', ctrlRoomId,
                   'tableId=', tableId,
                   'seatId=', seatId,
                   'contentItem=', contentItem)
Ejemplo n.º 41
0
    def openRedEnvelope(self, userId, itemId=''):
        '''
        打开红包
        '''
        global _redEnvelopeConfig

        # 是否领取过
        receivers = daobase.executeMixCmd('LRANGE', self.dbPrefix + self.id + self.RECEIVER, 0, -1)
        if receivers:
            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope receivers:', receivers)

            for receiverJson in receivers:
                receiver = json.loads(receiverJson)
                if ftlog.is_debug():
                    ftlog.debug('TYRedEnvelope.openRedEnvelope receiver:', receiver)
                if userId == receiver['userId']:
                    return False, _redEnvelopeConfig['tips']['opened']

        # 构造添加给获取红包用户的奖励清单        
        contentItemList = []
        prizesJson = self._getPrize(itemId)
        # prizesJson = daobase.executeMixCmd('LPOP', self.dbPrefix + self.id + self.PACKAGES)
        daobase.executeMixCmd('expire', self.dbPrefix + self.id + self.PACKAGES, self.expiredTime)

        if prizesJson:
            prizes = json.loads(prizesJson)
            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope prizes:', prizes)
            for prize in prizes:
                if ftlog.is_debug():
                    ftlog.debug('TYRedEnvelope.openRedEnvelope prize:', prize)

                result, _itemId = self.getAssetID(prize)
                if result == False:
                    ftlog.debug('TYRedEnvelope.openRedEnvelope prize err1: ', prize, ' left: ', self.contents);
                    continue

                result, value = self.getItemValue(prize)
                if result == False:
                    ftlog.debug('TYRedEnvelope.openRedEnvelope prize err2: ', prize, ' left: ', self.contents);
                    continue

                if ftlog.is_debug():
                    ftlog.debug('TYRedEnvelope.openRedEnvelope itemId:', _itemId)
                    ftlog.debug('TYRedEnvelope.openRedEnvelope count:', prizes[prize] * value)

                contentItemList.append(
                    TYContentItem.decodeFromDict({'itemId': _itemId, 'count': prizes[prize] * value}))

            if ftlog.is_debug():
                ftlog.debug('contentItemList:', contentItemList)

            userAssets = hallitem.itemSystem.loadUserAssets(userId)
            # 添加奖励
            results = userAssets.sendContentItemList(HALL_GAMEID, contentItemList, 1, True,
                                                     pktimestamp.getCurrentTimestamp(), self.EVENTID, 0)
            # notify
            datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, TYAssetUtils.getChangeDataNames(results))
            # 构造奖励字符串
            prizeString = TYAssetUtils.buildContentsString(results)

            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope prizeString:', prizeString)

            # add receiver
            re = {}
            re['userId'] = userId
            re['prize'] = prizes
            re['prizeStr'] = prizeString
            re['time'] = pktimestamp.formatTimeMs()

            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope add receiver re: ', re)
            daobase.executeMixCmd('LPUSH', self.dbPrefix + self.id + self.RECEIVER, json.dumps(re))
            daobase.executeMixCmd('expire', self.dbPrefix + self.id + self.RECEIVER, self.expiredTime)

            # make response
            response = {}
            response['envelopeId'] = self.id
            response['prizes'] = prizes
            response['prizeStr'] = prizeString

            if ftlog.is_debug():
                ftlog.debug('TYRedEnvelope.openRedEnvelope response: ', response)

            return True, response
        else:
            if self.state != self.STATE_FINISH:
                self.state = self.STATE_FINISH
                self.save2DB()

            return False, _redEnvelopeConfig['tips']['finished']