Пример #1
0
def sendShareForWXRedEnvelope(userId, record, item):
    try:
        action = item.itemKind.findActionByName('exchange')
        from hall.entity.hallitem import TYItemActionExchange
        if isinstance(
                action,
                TYItemActionExchange) and action.isWechatRedPack():  # 微信红包
            from poker.util import strutil
            from poker.entity.dao import sessiondata
            clientId = sessiondata.getClientId(userId)
            _, cVer, _ = strutil.parseClientId(clientId)
            if cVer >= 3.90:
                from hall.entity import hallshare
                gameId = strutil.getGameIdFromHallClientId(clientId)
                shareId = hallshare.getShareId('wxRedEnvelope', userId, gameId)
                share = hallshare.findShare(shareId)
                if share:
                    todotask = share.buildTodotask(HALL_GAMEID, userId,
                                                   'wxRedEnvelope')
                    if todotask:
                        from hall.entity.todotask import TodoTaskHelper
                        TodoTaskHelper.sendTodoTask(gameId, userId, todotask)
    except:
        ftlog.error('sendShareForWXRedEnvelope', 'userId=', userId,
                    'exchangeId=', record.exchangeId, 'itemId=', item.itemId,
                    'itemKindId=', item.kindId)
Пример #2
0
    def sendBenefits(self, gameId, userId, timestamp=None):
        '''
        发放救济金
        @return: isSend(True/False), TYUserBenefits
        '''
        if timestamp is None:
            timestamp = pktimestamp.getCurrentTimestamp()
        chip = pkuserchip.getUserChipAll(userId)
        if chip < self._minChip:
            # 用户金币低于指定数目时,发放救济金
            userBenefits = self.loadUserBenefits(gameId, userId, timestamp)
            if not userBenefits.hasLeftTimes():  # 没有剩余次数,弹分享引导
                oldtime = gamedata.getGameAttr(userId, HALL_GAMEID, 'relief_share_date')
                if not oldtime or datetime.fromtimestamp(oldtime).date() < datetime.fromtimestamp(timestamp).date():
                    # 每天最多弹一次
                    gamedata.setGameAttr(userId, HALL_GAMEID, 'relief_share_date', timestamp)
                    shareId = hallshare.getShareId('Relieffund', userId, gameId)
                    share = hallshare.findShare(shareId)
                    if share:
                        task = share.buildTodotask(gameId, userId, 'Relieffund')
                        TodoTaskHelper.sendTodoTask(gameId, userId, task)
                return False, userBenefits

            # 发放救济金
            userBenefits.times += 1
            self._benefitsDao.saveUserBenefitsData(userId, TYUserBenefitsData(userBenefits.times, timestamp))
            self._sendBenefits(gameId, userBenefits)
            # 通知用户金币刷新
            datachangenotify.sendDataChangeNotify(gameId, userId, ['udata'])
            return True, userBenefits
        return False, self.loadUserBenefits(gameId, userId, timestamp)
Пример #3
0
def getMatchShareInfo(userName, raceName, rank, reward, userId, condiction,
                      clientId):
    DIZHU_GAMEID = 6
    shareIds = getNewShareInfoByCondiction(DIZHU_GAMEID, clientId,
                                           condiction).get('shareIds', {})
    rewardInfo = getNewShareInfoByCondiction(DIZHU_GAMEID, clientId,
                                             condiction).get('rewardInfo', {})
    shareId = shareIds.get('weixin', 0) if shareIds else None
    if not shareId:
        return None

    share = hallshare.findShare(shareId)
    params = {
        'userName': userName,
        'raceName': raceName,
        'rank': rank,
        'reward': reward
    }

    todotask = share.buildTodotask(DIZHU_GAMEID, userId, 'diploma_share')
    desc = todotask.getParam('des', '')
    todotask.setParam('des', strutil.replaceParams(desc, params))

    todotaskDict = todotask.toDict()
    todotaskDict['rewardInfo'] = rewardInfo if rewardInfo else None

    if ftlog.is_debug():
        ftlog.debug('getMatchShareInfo userId=', userId, 'shareId=', shareId,
                    'userName='******'raceName=', raceName, 'rank=',
                    rank, 'reward=', reward, 'condiction=', condiction)

    return todotaskDict
Пример #4
0
    def get_award(self, uid):
        if not self.checkOperative():
            return 'acitivity expired!'

        actkey = ACTIVITY_KEY.format(HALL_GAMEID, uid, self.getid())
        weekcnt, daycnt = self._get_click_cnt(uid, actkey)
        if weekcnt >= self._clientConf['config'][
                'weeklimit'] or daycnt >= self._clientConf['config'][
                    'daylimit']:
            return 'awardcnt:({},{}) expand limitcnt!'.format(weekcnt, daycnt)

        shareid = self._serverConf["share"]
        share = hallshare.findShare(shareid)
        if not share:
            return 'share:{} not exist!'.format(shareid)

        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_DAY_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_WEEK_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_TOTAL_CNT, 1)
        hallshare.sendReward(HALL_GAMEID, uid, share, 'share_click')
        # 分享BI日志汇报
        clientid = sessiondata.getClientId(uid)
        bireport.reportGameEvent('SHARE_CALLBACK', uid, HALL_GAMEID, shareid,
                                 0, 0, 0, 0, 0, [], clientid)
        if share.mail:
            message.send(HALL_GAMEID, message.MESSAGE_TYPE_SYSTEM, uid,
                         share.mail)
        return 'ok'
Пример #5
0
 def doQueryDailyFreeGive(self, gameId, userId, shareId, clientId):
     try:
         mo = MsgPack()
         mo.setCmd('daily_free_give')
         mo.setResult('action', 'query')
         mo.setResult('dailyFreeGive',
                      daily_free_give.queryDailyFreeGive(userId, gameId))
         mo.setResult(
             'todayCheckIn',
             sevendayscheckin.loadStatus(userId, gameId).isTodayCheckined())
         share = hallshare.findShare(shareId)
         if share:
             shareInfo = hallshare.getShareStatus(
                 userId, share, pktimestamp.getCurrentTimestamp())
             mo.setResult('shareRewardCount', shareInfo[1])
         else:
             mo.setResult('shareRewardCount', 0)
         router.sendToUser(mo, userId)
         #统计
         bireport.reportGameEvent('SZMJ_DAILY_FREE_GIVE_QUERY', userId,
                                  gameId, 0, 0, 0, 0, 0, 0, [], clientId)
     except Exception as e:
         mo = MsgPack()
         mo.setCmd('daily_free_give')
         mo.setResult('action', 'query')
         mo.setError(e.errorCode, e.message)
         router.sendToUser(mo, userId)
Пример #6
0
def sendTableInviteShareTodoTask(userId, gameId, tableNo, playMode, cardCount,
                                 contentStr):
    '''牌桌上邀请处理
    '''
    shareId = hallshare.getShareId('mj_invite_play_share', userId, gameId)
    if shareId:
        share = hallshare.findShare(shareId)
        if not share:
            return

        retDesc = ''
        play_mode_dict = majiang_conf.get_room_other_config(gameId).get(
            'playmode_desc_map', {})
        retDesc += play_mode_dict.get(playMode, '') if playMode else ''
        retDesc += contentStr
        ftlog.debug('sendTableInviteShareTodoTask last retDesc:', retDesc)
        share.setDesc(retDesc)

        title = share.title.getValue(userId, gameId)
        title = '房间号:' + tableNo + ',' + title
        share.setTitle(title)

        todotask = share.buildTodotask(gameId, userId, 'mj_invite_play_share')
        mo = TodoTaskHelper.makeTodoTaskMsg(gameId, userId, todotask)
        router.sendToUser(mo, userId)
Пример #7
0
def _needSendBenefits(userId, gameId, clientId):
    '''
    是否需要发放救济金
    :param userId:
    :param gameId:
    :param clientId:
    '''
    global fuzhou_config
    if not _checkConditions(userId, clientId):
        return None
    
    if not hallstartchip_fuzhou.isSentStartChip(userId):
        return None
    
    if userchip.getChip(userId) >= fuzhou_config['minChip']:
        return None
    
    shareId = hallshare.getShareId(fuzhou_config['shareKey'], userId, gameId)
    if not shareId:
        return None
    share = hallshare.findShare(shareId)
    if not share:
        return None
    
    ok, rewardCount = hallshare.checkCanReward(userId, share, pktimestamp.getCurrentTimestamp())
    if not ok or rewardCount > fuzhou_config['maxCount']:
        ftlog.info("hallbenefits_fuzhou daily count:%s is used up!" % fuzhou_config['maxCount'], "userId =", userId, "gameId =", gameId, "clientId =", clientId)
        return None
    return share
Пример #8
0
def getShareInfo(userId, gameId, shareKey):
    shareId = hallshare.getShareId(shareKey, userId, gameId)
    share = hallshare.findShare(shareId)
    if share:
        return share.getUrl(userId, gameId), share.getTitle(userId, gameId)
    else:
        return None, None
Пример #9
0
 def findShare(cls, clientId, playround):
     '''
     @return: share or None
     '''
     shareConf = dizhuconf.getClientShareConf(clientId, {})
     shareId = shareConf.get(cls.name, {}).get(str(playround), None)
     ftlog.debug('sendShare shareConf=', shareConf, "clientId=", clientId,
                 "playround=", playround, "shareId=", shareId)
     if not shareId:
         return None
     return hallshare.findShare(shareId)
Пример #10
0
    def buildQueryPrizeResponse(cls, gameId, userId, clientId):
        timestamp = pktimestamp.getCurrentTimestamp()
        conf = neituiguang.getConf()
        status = neituiguang.loadStatus(userId, timestamp)
        totalRewardCount = cls.calcTotalInvitationByState(
            status, Invitation.STATE_REWARD)
        availableRewardCount = cls.calcTotalInvitationByState(
            status, Invitation.STATE_ACCEPT)
        mo = MsgPack()
        mo.setCmd('promote_info')
        mo.setResult('action', 'query_prize')
        mo.setResult('detail', conf.prizeDetail)
        mo.setResult('imgUrl', conf.prizeImgUrl)
        mo.setResult('promoteCode', userId)

        shareId = hallshare.getShareId('neituiguang2', userId, gameId)
        share = hallshare.findShare(shareId)
        if share:
            mo.setResult('shareId', shareId)
            mo.setResult('shareLoc', conf.shareLoc)
            mo.setResult('weixinInviteDoc', share.getDesc(HALL_GAMEID, userId))
            mo.setResult('weixinInviteUrl', share.getUrl(HALL_GAMEID, userId))
            mo.setResult('smsInviteDoc', share.getSmsDesc(HALL_GAMEID, userId))

        totalRewardContent = ''
        if conf.prizeRewardItem:
            totalRewardContent = hallitem.buildContent(
                conf.prizeRewardItem.assetKindId,
                conf.prizeRewardItem.count * totalRewardCount)
        prizeGetedInfo = conf.prizeGotTotalRewardDesc if conf.prizeRewardItem and totalRewardCount else conf.prizeNotGotRewardDesc
        prizeGetedInfo = strutil.replaceParams(
            prizeGetedInfo, {'totalRewardContent': totalRewardContent})
        mo.setResult('prizeGetedInfo', prizeGetedInfo)

        availableRewardContent = ''
        if conf.prizeRewardItem:
            availableRewardContent = hallitem.buildContent(
                conf.prizeRewardItem.assetKindId,
                conf.prizeRewardItem.count * availableRewardCount)
        prizeAvailableInfo = conf.prizeAvailableRewardDesc if conf.prizeRewardItem else conf.prizeAvailableRewardDesc
        prizeAvailableInfo = strutil.replaceParams(
            prizeAvailableInfo,
            {'availableRewardContent': availableRewardContent})
        mo.setResult('prizeAvailableInfo', prizeAvailableInfo)

        prizeList = []
        invitationList = sorted(status.inviteeMap.values(),
                                key=lambda i: i.index)
        for invitation in invitationList:
            prizeList.append(cls.encodeInvitation(invitation))
        mo.setResult('prizeList', prizeList)
        mo.setResult('state', 1 if availableRewardCount > 0 else 0)
        return mo
Пример #11
0
def sendTableInviteShareTodoTask(userId, gameId, tableNo, playMode, cardCount, contentStr):
    '''牌桌上邀请处理
    '''
    shareId = hallshare.getShareId('mj_invite_play_share', userId, gameId)
    if shareId:
        share =  hallshare.findShare(shareId)
        if not share:
            return
        
        retDesc = ''
        play_mode_dict = majiang_conf.get_room_other_config(gameId).get('playmode_desc_map', {})

        if gameId == 715:
            retDesc = contentStr;
        else:
            retDesc += play_mode_dict.get(playMode,'') if playMode else ''
            retDesc += contentStr
        ftlog.debug('sendTableInviteShareTodoTask last retDesc:', retDesc)
        share.setDesc(retDesc)
        
        if gameId == 715:
            title = play_mode_dict.get(playMode,'') if playMode else ''
            title += ' - 房号:' + tableNo
        else:
            title = share.title.getValue(userId, gameId)
            title = '房间号:' + tableNo + ',' + title
        share.setTitle(title)
        ftlog.debug('sendTableInviteShareTodoTask newTitle:', title)
        
        url = share.url.getValue(userId, gameId)
        url += "?ftId=" + tableNo
        url += "?from=magicWindow"
        eParams = {}
        eParams['action'] = 'hall_enter_friend_table_direct'
        fParam = {}
        fParam['ftId'] = tableNo
        eParams['params'] = fParam
        paramStr = json.dumps(eParams)
        base64Str = base64.b64encode(paramStr)
        from urllib import quote
        url += "&enterParams=" + quote(base64Str)
        share.setUrl(url)
        ftlog.debug('sendTableInviteShareTodoTask newUrl:', url
                    , ' ftId:', tableNo
                    , ' paramStr:', paramStr
                    , ' base64Str:', base64Str)
        
        todotask = share.buildTodotask(gameId, userId, 'mj_invite_play_share')
        mo = TodoTaskHelper.makeTodoTaskMsg(gameId, userId, todotask)
        router.sendToUser(mo, userId)
Пример #12
0
    def _fill_button_todotask(self, userId, config, buttonname, replace_dict):
        button = config.get(buttonname)
        if not button:
            return

        if button['visible']:
            share = hallshare.findShare(button["todoTask"]["share"])
            if share:
                todotask = share.buildTodotask(HALL_GAMEID, userId, 'act_new_friend_invite', replace_dict)
                button["todoTask"] = todotask.toDict()
                return

        del config[buttonname]
        return
Пример #13
0
def sendTableInviteShareTodoTask(userId, gameId, tableNo, playMode, cardCount,
                                 contentStr):
    '''牌桌上邀请处理
    '''
    shareId = hallshare.getShareId('mj_invite_play_share', userId, gameId)
    if shareId:
        share = hallshare.findShare(shareId)
        if not share:
            return

        retDesc = ''
        play_mode_dict = majiang_conf.get_room_other_config(gameId).get(
            'playmode_desc_map', {})

        if gameId == 715:
            retDesc = contentStr
        else:
            retDesc += play_mode_dict.get(playMode, '') if playMode else ''
            retDesc += contentStr
        ftlog.debug('sendTableInviteShareTodoTask last retDesc:', retDesc)
        share.setDesc(retDesc)

        if gameId == 715:
            title = play_mode_dict.get(playMode, '') if playMode else ''
            title += ' - 房号:' + tableNo
        else:
            title = share.title.getValue(userId, gameId)
            title = '房间号:' + tableNo + ',' + title
        share.setTitle(title)
        ftlog.debug('sendTableInviteShareTodoTask newTitle:', title)

        url = share.url.getValue(userId, gameId)
        url += "?ftId=" + tableNo
        url += "?from=magicWindow"
        eParams = {}
        eParams['action'] = 'hall_enter_friend_table_direct'
        fParam = {}
        fParam['ftId'] = tableNo
        eParams['params'] = fParam
        paramStr = json.dumps(eParams)
        base64Str = base64.b64encode(paramStr)
        from urllib import quote
        url += "&enterParams=" + quote(base64Str)
        share.setUrl(url)
        ftlog.debug('sendTableInviteShareTodoTask newUrl:', url, ' ftId:',
                    tableNo, ' paramStr:', paramStr, ' base64Str:', base64Str)

        todotask = share.buildTodotask(gameId, userId, 'mj_invite_play_share')
        mo = TodoTaskHelper.makeTodoTaskMsg(gameId, userId, todotask)
        router.sendToUser(mo, userId)
    def _fill_button_todotask(self, userId, config, buttonname, replace_dict):
        button = config.get(buttonname)
        if not button:
            return

        if button['visible']:
            share = hallshare.findShare(button["todoTask"]["share"])
            if share:
                todotask = share.buildTodotask(HALL_GAMEID, userId,
                                               'act_new_friend_invite',
                                               replace_dict)
                button["todoTask"] = todotask.toDict()
                return

        del config[buttonname]
        return
Пример #15
0
    def _getShareReward(self, gameId, userId, shareId, shareLoc, code):
        if (shareId == '-') or (shareId == '-1') or (code != 0):
            ftlog.debug('ShareTcpHandler._getShareReward gameId=', gameId,
                        'userId=', userId, 'shareId=', shareId, 'shareLoc=',
                        shareLoc, 'code=', code, 'err=', 'BadShareId')
            return

        share = hallshare.findShare(int(shareId))
        if not share:
            ftlog.debug('ShareTcpHandler._getShareReward gameId=', gameId,
                        'userId=', userId, 'shareId=', shareId, 'shareLoc=',
                        shareLoc, 'code=', code, 'err=', 'UnknownShareId')
            return

        hallshare.getShareReward(gameId, userId, share, shareLoc,
                                 pktimestamp.getCurrentTimestamp())
Пример #16
0
    def getConfigForClient(self, gameId, userId, clientId):
        client = copy.deepcopy(self._clientConf)
        shareid = self._serverConf['share']
        share = hallshare.findShare(shareid)
        if share:
            winrate = gamedata.getGameAttr(userId, 6, 'winrate')
            winrate = strutil.loads(winrate, ignoreException=True, execptionValue={})
            todotask = share.buildTodotask(HALL_GAMEID, userId, 'share_click',
                                           {'userId': userId, 'actName': client['id'],
                                            'dizhuPlayNum': winrate.get('pt', 0)})
            client['config']["share"] = todotask.toDict()

        actkey = ACTIVITY_KEY.format(HALL_GAMEID, userId, client['id'])
        total = daobase.executeUserCmd(userId, 'HGET', actkey, self.FIELD_TOTAL_CNT)
        client['config']['total'] = total if total else 0
        client['config']['today'] = self._get_click_cnt(userId, actkey)[1]
        return client
Пример #17
0
    def buildQueryPrizeResponse(cls, gameId, userId, clientId):
        timestamp = pktimestamp.getCurrentTimestamp()
        conf = neituiguang.getConf()
        status = neituiguang.loadStatus(userId, timestamp)
        totalRewardCount = cls.calcTotalInvitationByState(status, Invitation.STATE_REWARD)
        availableRewardCount = cls.calcTotalInvitationByState(status, Invitation.STATE_ACCEPT)
        mo = MsgPack()
        mo.setCmd('promote_info')
        mo.setResult('action', 'query_prize')
        mo.setResult('detail', conf.prizeDetail)
        mo.setResult('imgUrl', conf.prizeImgUrl)
        mo.setResult('promoteCode', userId)

        shareId = hallshare.getShareId('neituiguang2', userId, gameId)
        share = hallshare.findShare(shareId)
        if share:
            mo.setResult('shareId', shareId)
            mo.setResult('shareLoc', conf.shareLoc)
            mo.setResult('weixinInviteDoc', share.getDesc(HALL_GAMEID, userId))
            mo.setResult('weixinInviteUrl', share.getUrl(HALL_GAMEID, userId))
            mo.setResult('smsInviteDoc', share.getSmsDesc(HALL_GAMEID, userId))

        totalRewardContent = ''
        if conf.prizeRewardItem:
            totalRewardContent = hallitem.buildContent(conf.prizeRewardItem.assetKindId,
                                                       conf.prizeRewardItem.count * totalRewardCount)
        prizeGetedInfo = conf.prizeGotTotalRewardDesc if conf.prizeRewardItem and totalRewardCount else conf.prizeNotGotRewardDesc
        prizeGetedInfo = strutil.replaceParams(prizeGetedInfo, {'totalRewardContent': totalRewardContent})
        mo.setResult('prizeGetedInfo', prizeGetedInfo)

        availableRewardContent = ''
        if conf.prizeRewardItem:
            availableRewardContent = hallitem.buildContent(conf.prizeRewardItem.assetKindId,
                                                           conf.prizeRewardItem.count * availableRewardCount)
        prizeAvailableInfo = conf.prizeAvailableRewardDesc if conf.prizeRewardItem else conf.prizeAvailableRewardDesc
        prizeAvailableInfo = strutil.replaceParams(prizeAvailableInfo,
                                                   {'availableRewardContent': availableRewardContent})
        mo.setResult('prizeAvailableInfo', prizeAvailableInfo)

        prizeList = []
        invitationList = sorted(status.inviteeMap.values(), key=lambda i: i.index)
        for invitation in invitationList:
            prizeList.append(cls.encodeInvitation(invitation))
        mo.setResult('prizeList', prizeList)
        mo.setResult('state', 1 if availableRewardCount > 0 else 0)
        return mo
Пример #18
0
    def buildShareTask(self,
                       userId,
                       gameId,
                       url=None,
                       title=None,
                       desc=None,
                       tips=None,
                       shareIcon=None):
        '''
        获取分享ID
        url - 红包分享页面的URL
        title - 红包分享时的标题
        desc - 红包分享时的描述
        tips - 游戏触发分享时的提醒
        shareIcon - 分享后的图片
        '''
        from hall.entity import hallshare

        global _redEnvelopeConfig

        shareId = hallshare.getShareId('red_envelope', userId, gameId)
        share = hallshare.findShare(shareId)
        if share:
            if url:
                share.setUrl(url)

            if title:
                share.setTitle(title)

            if desc:
                share.setDesc(desc)

            if tips:
                share.setTips(tips)

            if shareIcon:
                share.setShareIcon(shareIcon)

            # 设置分享的扩展参数
            share.setNotifyInfo(userId, self.id, self.EVENTID)

            return share.buildTodotask(gameId, userId, 'red_envelope')
        else:
            return None
Пример #19
0
def buildDiplomaShare(userName, raceName, rank, reward, userId):
    shareId = dizhuconf.getPublicConf('diplomaShareId', 0)
    ftlog.debug('buildDiplomaShare shareId = ', shareId)
    if shareId <= 0:
        return None

    share = hallshare.findShare(shareId)
    # build share todotask
    params = {
        'userName': userName,
        'raceName': raceName,
        'rank': rank,
        'reward': reward
    }

    todotask = share.buildTodotask(DIZHU_GAMEID, userId, 'diploma_share')
    desc = todotask.getParam('des', '')
    todotask.setParam('des', strutil.replaceParams(desc, params))

    return todotask.toDict()
Пример #20
0
    def _getShareReward(self, gameId, userId, shareId, shareLoc, code):
        if (shareId == '-') or (shareId == '-1') or (code != 0):
            ftlog.debug('ShareTcpHandler._getShareReward gameId=', gameId,
                        'userId=', userId,
                        'shareId=', shareId,
                        'shareLoc=', shareLoc,
                        'code=', code,
                        'err=', 'BadShareId')
            return

        share = hallshare.findShare(int(shareId))
        if not share:
            ftlog.debug('ShareTcpHandler._getShareReward gameId=', gameId,
                        'userId=', userId,
                        'shareId=', shareId,
                        'shareLoc=', shareLoc,
                        'code=', code,
                        'err=', 'UnknownShareId')
            return

        hallshare.getShareReward(gameId, userId, share, shareLoc, pktimestamp.getCurrentTimestamp())
Пример #21
0
def inviteFriend(userId, ftTable):
    creatorConf = getCreatorConf(userId)
    share = hallshare.findShare(creatorConf.inviteShareId)
    if ftlog.is_debug():
        ftlog.debug('ft_service.inviteFriend',
                    'userId=', userId,
                    'ftId=', ftTable.ftId,
                    'shareId=', creatorConf.inviteShareId,
                    'share=', share)
    if share:
        params = {
            'ftId':ftTable.ftId,
            'playMode':ftTable.playMode.get('displayName', ''),
            'nRound':ftTable.nRound,
            'canDouble':'可加倍' if ftTable.canDouble else '不可加倍'
        }
        todotask = share.buildTodotask(DIZHU_GAMEID, userId, 'ftInvite', params)
        title = todotask.getParam('title', '')
        des = todotask.getParam('des', '')
        todotask.setParam('title', strutil.replaceParams(title, params))
        todotask.setParam('des', strutil.replaceParams(des, params))
        return TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, todotask)
    return None
Пример #22
0
def sendTableInviteShareTodoTask(userId, gameId, tableNo, playMode, cardCount, contentStr):
    '''牌桌上邀请处理
    '''
    shareId = hallshare.getShareId('mj_invite_play_share', userId, gameId)
    if shareId:
        share = hallshare.findShare(shareId)
        if not share:
            return

        retDesc = ''
        play_mode_dict = majiang_conf.get_room_other_config(gameId).get('playmode_desc_map', {})
        retDesc += play_mode_dict.get(playMode, '') if playMode else ''
        retDesc += contentStr
        ftlog.debug('sendTableInviteShareTodoTask last retDesc:', retDesc)
        share.setDesc(retDesc)

        title = share.title.getValue(userId, gameId)
        title = '房间号:' + tableNo + ',' + title
        share.setTitle(title)

        todotask = share.buildTodotask(gameId, userId, 'mj_invite_play_share')
        mo = TodoTaskHelper.makeTodoTaskMsg(gameId, userId, todotask)
        router.sendToUser(mo, userId)
Пример #23
0
    def getConfigForClient(self, gameId, userId, clientId):
        client = copy.deepcopy(self._clientConf)
        shareid = self._serverConf['share']
        share = hallshare.findShare(shareid)
        if share:
            winrate = gamedata.getGameAttr(userId, 6, 'winrate')
            winrate = strutil.loads(winrate,
                                    ignoreException=True,
                                    execptionValue={})
            todotask = share.buildTodotask(
                HALL_GAMEID, userId, 'share_click', {
                    'userId': userId,
                    'actName': client['id'],
                    'dizhuPlayNum': winrate.get('pt', 0)
                })
            client['config']["share"] = todotask.toDict()

        actkey = ACTIVITY_KEY.format(HALL_GAMEID, userId, client['id'])
        total = daobase.executeUserCmd(userId, 'HGET', actkey,
                                       self.FIELD_TOTAL_CNT)
        client['config']['total'] = total if total else 0
        client['config']['today'] = self._get_click_cnt(userId, actkey)[1]
        return client
Пример #24
0
    def buildShareTask(self, userId, gameId, url=None, title=None, desc=None, tips=None, shareIcon=None):
        '''
        获取分享ID
        url - 红包分享页面的URL
        title - 红包分享时的标题
        desc - 红包分享时的描述
        tips - 游戏触发分享时的提醒
        shareIcon - 分享后的图片
        '''
        from hall.entity import hallshare

        global _redEnvelopeConfig

        shareId = hallshare.getShareId('red_envelope', userId, gameId)
        share = hallshare.findShare(shareId)
        if share:
            if url:
                share.setUrl(url)

            if title:
                share.setTitle(title)

            if desc:
                share.setDesc(desc)

            if tips:
                share.setTips(tips)

            if shareIcon:
                share.setShareIcon(shareIcon)

            # 设置分享的扩展参数    
            share.setNotifyInfo(userId, self.id, self.EVENTID)

            return share.buildTodotask(gameId, userId, 'red_envelope')
        else:
            return None
Пример #25
0
    def get_award(self, uid):
        if not self.checkOperative():
            return 'acitivity expired!'

        actkey = ACTIVITY_KEY.format(HALL_GAMEID, uid, self.getid())
        weekcnt, daycnt = self._get_click_cnt(uid, actkey)
        if weekcnt >= self._clientConf['config']['weeklimit'] or daycnt >= self._clientConf['config']['daylimit']:
            return 'awardcnt:({},{}) expand limitcnt!'.format(weekcnt, daycnt)

        shareid = self._serverConf["share"]
        share = hallshare.findShare(shareid)
        if not share:
            return 'share:{} not exist!'.format(shareid)

        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_DAY_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_WEEK_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_TOTAL_CNT, 1)
        hallshare.sendReward(HALL_GAMEID, uid, share, 'share_click')
        # 分享BI日志汇报
        clientid = sessiondata.getClientId(uid)
        bireport.reportGameEvent('SHARE_CALLBACK', uid, HALL_GAMEID, shareid, 0, 0, 0, 0, 0, [], clientid)
        if share.mail:
            message.send(HALL_GAMEID, message.MESSAGE_TYPE_SYSTEM, uid, share.mail)
        return 'ok'
Пример #26
0
    def buildActivityInfo(self, userId, usermodel=None):
        clientconf = copy.deepcopy(self._clientConf)
        if not usermodel:
            usermodel = UserModel.loadModel(self.activityGameId,
                                            self._clientConf['id'], userId)

        # 分享按钮显示与消失
        # 小红包按钮上的文字显示
        # 倒计时时间
        # 大红包按钮上的文字显示
        # 小红包上的提示文字显示

        # 默认不显示分享按钮
        clientconf['config']['client']['buttonShare']['visible'] = False

        currentDuration = self.openList.getCurrentDurationItem()
        if currentDuration:
            # 正在抢红包时间段
            clientconf['config']['client']['secondsStart'] = 0
            clientconf['config']['client'][
                'secondsStop'] = currentDuration.getEndLeftSeconds()
            # 是否已经抢过红包
            issueNumber = currentDuration.getIssueNumber()
            if ftlog.is_debug():
                ftlog.debug('LuckyMoneyNew.buildActivityInfo:currentDuration',
                            'userId=', userId, 'activityId=', clientconf['id'],
                            'issueNumber=', issueNumber, 'hadGrabbed=',
                            usermodel.hadGrabbed(issueNumber), 'hadShared=',
                            usermodel.hadShared(issueNumber), 'lastPrize=',
                            usermodel.lastPrize)
            # 若玩家已经已抢过此期红包
            if usermodel.hadGrabbed(issueNumber):
                # 主按钮提示已抢到
                clientconf['config']['client']['buttonMain'][
                    'title'] = clientconf['config']['client']['buttonMain'][
                        'title.grabbed']
                # 抢到的红包奖励,分享奖励,或者啥也没抢到的信息
                clientconf['config']['client'][
                    'prizeInfo'] = self.buildPrizeContent(usermodel.lastPrize)
                # 存在已经抢到的奖励或者分享获得的奖励
                if not usermodel.lastPrize:
                    clientconf['config']['client']['buttonShare'][
                        'visible'] = True
                    share = hallshare.findShare(
                        clientconf['config']['server']['shareId'])
                    if share:
                        todotask = share.buildTodotask(self.activityGameId,
                                                       userId, None)
                        clientconf['config']['client']['buttonShare'][
                            'todotask'] = todotask.toDict()
                    # 红包被抢光,用户没有奖励
                    clientconf['config']['client']['labelTip'] = clientconf[
                        'config']['client']['labelTip.grabbed_null']
                else:
                    if usermodel.hadShared(issueNumber):
                        clientconf['config']['client'][
                            'labelTip'] = clientconf['config']['client'][
                                'labelTip.shared']
                    else:
                        clientconf['config']['client'][
                            'labelTip'] = clientconf['config']['client'][
                                'labelTip.gained']
            else:
                # 抢红包
                clientconf['config']['client']['buttonMain'][
                    'title'] = clientconf['config']['client']['buttonMain'][
                        'title.grab']
        else:
            nextDuration = self.openList.getNextDurationItem()
            clientconf['config']['client'][
                'secondsStart'] = nextDuration.getStartLeftSeconds(
                ) if nextDuration else 0
            clientconf['config']['client'][
                'secondsStop'] = nextDuration.getEndLeftSeconds(
                ) if nextDuration else 0
            if nextDuration:
                # 未开始
                clientconf['config']['client']['buttonMain'][
                    'title'] = clientconf['config']['client']['buttonMain'][
                        'title.unstart']
            else:
                # 已结束
                clientconf['config']['client']['buttonMain'][
                    'title'] = clientconf['config']['client']['buttonMain'][
                        'title.final']
        return clientconf
Пример #27
0
def handleShippingResult1(userId, exchangeId, result):
    '''
    发货结果处理
    '''
    if ftlog.is_debug():
        ftlog.debug('enter handleShippingResult(), userId:', userId,
                    'exchangeId:', exchangeId, 'result:', result)

    record = loadRecord(userId, exchangeId)
    if not record:
        raise TYUnknownExchangeOrder()
    if record.state != TYExchangeRecord.STATE_ACCEPT:
        raise TYBadStateExchangeOrder()

    userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
    item = userBag.findItem(record.itemId)

    if not isinstance(item, TYExchangeItem):
        raise TYBizException(-1, '系统错误')

    if item.state != TYExchangeItem.STATE_SHIPPING:
        raise TYBizException(-1, '道具状态错误')

    timestamp = pktimestamp.getCurrentTimestamp()

    if result == RESULT_OK:
        record.state = TYExchangeRecord.STATE_SHIPPING_SUCC
        userBag.removeItem(HALL_GAMEID, item, timestamp, 'EXCHANGE',
                           item.kindId)
    elif result == RESULT_SHIPPINGFAIL_RETURN:
        record.state = TYExchangeRecord.STATE_SHIPPING_FAIL_RETURN
        item.state = TYExchangeItem.STATE_NORMAL
        userBag.updateItem(HALL_GAMEID, item, timestamp)
    elif result == RESULT_SHIPPINGFAIL:
        record.state = TYExchangeRecord.STATE_SHIPPING_FAIL
        userBag.removeItem(HALL_GAMEID, item, timestamp, 'EXCHANGE',
                           item.kindId)
    else:
        raise TYBizException(-1, '错误的请求状态')

    itemDisPlayName = item.itemKind.displayName
    exchangeDesc = record.params.get('desc', '')
    if result == RESULT_OK:
        mail = '您申请用%s兑换(领取)%s,已成功为您办理,请查收。' % (itemDisPlayName, exchangeDesc)
    else:
        mail = '您申请用%s兑换(领取)%s,审核未通过,抱歉。' % (itemDisPlayName, exchangeDesc)

    pkmessage.send(HALL_GAMEID, pkmessage.MESSAGE_TYPE_SYSTEM, userId, mail)
    datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, 'message')

    if result == RESULT_OK:
        action = item.itemKind.findActionByName('exchange')
        from hall.entity.hallitem import TYItemActionExchange
        if isinstance(
                action,
                TYItemActionExchange) and action.isWechatRedPack():  # 微信红包
            from poker.util import strutil
            from poker.entity.dao import sessiondata
            clientId = sessiondata.getClientId(userId)
            _, cVer, _ = strutil.parseClientId(clientId)
            if cVer >= 3.90:
                from hall.entity import hallshare
                gameId = strutil.getGameIdFromHallClientId(clientId)
                shareId = hallshare.getShareId('wxRedEnvelope', userId, gameId)
                share = hallshare.findShare(shareId)
                if share:
                    todotask = share.buildTodotask(HALL_GAMEID, userId,
                                                   'wxRedEnvelope')
                    if todotask:
                        from hall.entity.todotask import TodoTaskHelper
                        TodoTaskHelper.sendTodoTask(gameId, userId, todotask)

    jstr = json.dumps(record.toDict())
    _saveRecordData(userId, exchangeId, jstr)

    ftlog.info('hallexchange.handleShippingResult1', 'userId=', userId,
               'exchangeId=', exchangeId, 'result=', result, 'itemId=',
               item.itemId, 'itemKindId=', item.kindId, 'orderState=',
               record.state)

    return record
Пример #28
0
 def _findShareByPlayRound(self, playRound):
     for s in self._shares:
         if s['playRound'] == playRound:
             return hallshare.findShare(s['shareId'])
     return None
Пример #29
0
def exchangeProduct(gameId, userId, clientId, orderId, productId, count):
    product = storeSystem.findProduct(productId)
    if not product:
        raise TYBuyProductUnknownException(productId)

    if product.buyType != 'exchange':
        raise TYProductNotSupportExchangeException(productId)

    timestamp = pktimestamp.getCurrentTimestamp()

    # 限购系统锁定
    periodId = hallstocklimit.productBuyLimitSystem.lockProduct(gameId, userId, productId, count, timestamp)

    # 创建订单
    try:
        storeSystem.buyProduct(gameId, userId, clientId, orderId, productId, count)
    except:
        if periodId:
            hallstocklimit.productBuyLimitSystem.unlockProduct(gameId, userId, periodId, productId,
                                                               count, 1, timestamp)
        raise

    # 
    ftlog.info('hallstore.exchangeProduct gameId=', gameId,
               'userId=', userId,
               'clientId=', clientId,
               'orderId=', orderId,
               'productId=', productId,
               'count=', count)

    try:
        # 消耗兑换的东西
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetTuple = userAssets.consumeAsset(gameId, product.exchangeFeeContentItem.assetKindId,
                                             product.exchangeFeeContentItem.count * count,
                                             timestamp,
                                             'BUY_PRODUCT', pokerconf.productIdToNumber(productId))
        if assetTuple[1] < product.exchangeFeeContentItem.count * count:
            ftlog.warn('hallstore.exchangeProduct gameId=', gameId,
                       'userId=', userId,
                       'clientId=', clientId,
                       'orderId=', orderId,
                       'productId=', productId,
                       'count=', count,
                       'consumedCount=', assetTuple[1],
                       'needConsumeCount=', product.exchangeFeeContentItem.count * count,
                       'err=', 'ConsumeNotEnough')
            msg = strutil.replaceParams(product.exchangeFeeNotEnoughText, {'feeName': assetTuple[0].displayName})
            raise TYProductExchangeNotEnoughException(productId, msg)

        datachangenotify.sendDataChangeNotify(gameId, userId, TYAssetUtils.getChangeDataNames([assetTuple]))
        consumeMap = {assetTuple[0].kindId: assetTuple[1]}
        ret = storeSystem.deliveryOrder(userId, orderId, productId, TYChargeInfo('', {}, consumeMap))

        # 分享提示
        shareId = hallshare.getShareId('exchangeShare', userId, gameId)
        if ftlog.is_debug():
            ftlog.debug('handleExchangeAuditResult shareId: ', shareId)

        share = hallshare.findShare(shareId)
        if share:
            desc = share.getDesc(gameId, userId, True)
            newDesc = strutil.replaceParams(desc, {'exchangeDesc': product.displayName})
            share.setDesc(newDesc)
            task = share.buildTodotask(HALL_GAMEID, userId, 'exchange')
            TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, task)

        if periodId:
            hallstocklimit.productBuyLimitSystem.deliveryProduct(gameId, userId, periodId, productId, count, timestamp)
        return ret
    except:
        if periodId:
            hallstocklimit.productBuyLimitSystem.unlockProduct(gameId, userId, periodId, productId, count, 2, timestamp)
        raise
Пример #30
0
def exchangeProduct(gameId, userId, clientId, orderId, productId, count):
    product = storeSystem.findProduct(productId)
    if not product:
        raise TYBuyProductUnknownException(productId)

    if product.buyType != 'exchange':
        raise TYProductNotSupportExchangeException(productId)

    timestamp = pktimestamp.getCurrentTimestamp()

    # 限购系统锁定
    periodId = hallstocklimit.productBuyLimitSystem.lockProduct(
        gameId, userId, productId, count, timestamp)

    # 创建订单
    try:
        storeSystem.buyProduct(gameId, userId, clientId, orderId, productId,
                               count)
    except:
        if periodId:
            hallstocklimit.productBuyLimitSystem.unlockProduct(
                gameId, userId, periodId, productId, count, 1, timestamp)
        raise

    #
    ftlog.info('hallstore.exchangeProduct gameId=', gameId, 'userId=', userId,
               'clientId=', clientId, 'orderId=', orderId, 'productId=',
               productId, 'count=', count)

    try:
        # 消耗兑换的东西
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetTuple = userAssets.consumeAsset(
            gameId, product.exchangeFeeContentItem.assetKindId,
            product.exchangeFeeContentItem.count * count, timestamp,
            'BUY_PRODUCT', pokerconf.productIdToNumber(productId))
        if assetTuple[1] < product.exchangeFeeContentItem.count * count:
            ftlog.warn('hallstore.exchangeProduct gameId=', gameId, 'userId=',
                       userId, 'clientId=', clientId, 'orderId=', orderId,
                       'productId=', productId, 'count=', count,
                       'consumedCount=', assetTuple[1], 'needConsumeCount=',
                       product.exchangeFeeContentItem.count * count, 'err=',
                       'ConsumeNotEnough')
            msg = strutil.replaceParams(product.exchangeFeeNotEnoughText,
                                        {'feeName': assetTuple[0].displayName})
            raise TYProductExchangeNotEnoughException(productId, msg)

        datachangenotify.sendDataChangeNotify(
            gameId, userId, TYAssetUtils.getChangeDataNames([assetTuple]))
        consumeMap = {assetTuple[0].kindId: assetTuple[1]}
        ret = storeSystem.deliveryOrder(userId, orderId, productId,
                                        TYChargeInfo('', {}, consumeMap))

        # 分享提示
        shareId = hallshare.getShareId('exchangeShare', userId, gameId)
        if ftlog.is_debug():
            ftlog.debug('handleExchangeAuditResult shareId: ', shareId)

        share = hallshare.findShare(shareId)
        if share:
            desc = share.getDesc(gameId, userId, True)
            newDesc = strutil.replaceParams(
                desc, {'exchangeDesc': product.displayName})
            share.setDesc(newDesc)
            task = share.buildTodotask(HALL_GAMEID, userId, 'exchange')
            TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, task)

        if periodId:
            hallstocklimit.productBuyLimitSystem.deliveryProduct(
                gameId, userId, periodId, productId, count, timestamp)
        return ret
    except:
        if periodId:
            hallstocklimit.productBuyLimitSystem.unlockProduct(
                gameId, userId, periodId, productId, count, 2, timestamp)
        raise
Пример #31
0
    def getUserCollectList(self, userId):
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        ret = []
        for socks in self._collectItemList:
            itemConf = self._collectItemList[socks]
            itemId = itemConf.get('itemId')
            itemCount = itemConf.get('count')
            balance = userAssets.balance(HALL_GAMEID, itemId, pktimestamp.getCurrentTimestamp())
            todotask = itemConf.get('todotask')
            todotaskDict = None
            if todotask.get('shareId'):
                # 分享的todotask
                clientIdList = [20232, 20293, 20329, 20338, 20340, 20354, 20689, 20729, 21306, 21317, 21360, 21368,
                    21377, 21736, 20195, 20259, 20294, 20331, 20685, 20698, 21330, 21355, 21361, 21419, 20264, 20265,
                    20267, 20268, 20272, 20287, 20288, 20289, 20348, 20349, 20350, 20351, 20488, 20489, 20490, 20699,
                    20701, 20702, 20788, 20790, 20791, 21040, 21328, 21331, 21333, 21334, 21350, 21352, 21353, 21791,
                    21792, 21793, 21794, 22043]
                from poker.entity.dao import sessiondata
                _, intClientId = sessiondata.getClientIdNum(userId)
                if intClientId in clientIdList:
                    # 无法分享的包,弹出提示todotask
                    msg = u"今日登录已获得友谊之袜×1 明天再来吧~"
                    dialog_task = TodoTaskShowInfo(msg, True)
                    # TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, [dialog_task])
                    todotaskDict = dialog_task.toDict() if dialog_task else None
                else:
                    shareId = todotask.get('shareId')
                    share = hallshare.findShare(shareId)
                    todotask = share.buildTodotask(DIZHU_GAMEID, userId, 'diploma_share')
                    todotaskDict = todotask.toDict() if todotask else None
                if not todotaskDict:
                    ftlog.warn('christmas sharePointId not Found. userId=', userId)
                if ftlog.is_debug():
                    ftlog.debug('christmas.shareTodotask. userId=', userId, 'todotaskDict=', todotaskDict)

            elif todotask.get('sessionIndex'):
                # 生成快开的todotask
                jumpTodoTask = TodoTaskEnterGame("enter_game", "")
                enterParam = dict()
                enterParam["type"] = "quickstart"
                enterParam["pluginParams"] = {}
                enterParam["pluginParams"]["gameType"] = 1
                enterParam["pluginParams"]["sessionIndex"] = int(todotask.get('sessionIndex'))    #0-经典 1-欢乐 2-癞子 3-二人
                jumpTodoTask.setParam('gameId', DIZHU_GAMEID)
                jumpTodoTask.setParam('type', "quickstart")
                jumpTodoTask.setParam('enter_param', enterParam)
                if not jumpTodoTask:
                    ftlog.warn('christmas TodoTaskQuickStart not Found. userId=', userId)
                else:
                    todotaskDict = jumpTodoTask.toDict()

            elif todotask.get('matchIndex'):
                # 跳转比赛列表的todotask
                jumpTodoTask = TodoTaskEnterGame("enter_game", "")
                enterParam = dict()
                enterParam["type"] = "roomlist"
                enterParam["pluginParams"] = {}
                enterParam["pluginParams"]["gameType"] = 3
                enterParam["pluginParams"]["matchIndex"] = int(todotask.get('matchIndex'))    #0-比赛第一页 1-比赛第二页 2-比赛第三页
                jumpTodoTask.setParam('gameId', DIZHU_GAMEID)
                jumpTodoTask.setParam('type', "roomlist")
                jumpTodoTask.setParam('enter_param', enterParam)
                if not jumpTodoTask:
                    ftlog.warn('christmas TodoTaskEnterGame not Found. userId=', userId)
                else:
                    todotaskDict = jumpTodoTask.toDict()
            ret.append([itemId, balance, itemCount, todotaskDict])

        if ftlog.is_debug():
            ftlog.debug('christmas.getUserCollectList userId=', userId,
                        'collectList=', ret)
        return ret