def _checkSendCondition(userId, gameId, eventId, timeStamp):
    startTime = configure.getGameJson(DIZHU_GAMEID, 'official.message',
                                      {}).get('startTime')
    stopTime = configure.getGameJson(DIZHU_GAMEID, 'official.message',
                                     {}).get('stopTime')
    start = datetime.datetime.strptime(startTime, "%H:%M").time()
    stop = datetime.datetime.strptime(stopTime, "%H:%M").time()
    now = datetime.datetime.now().time()
    if start >= stop or now < start or now > stop:
        if ftlog.is_debug():
            ftlog.debug('wx_official._checkSendCondition', 'userId=', userId,
                        'gameId=', gameId, 'start=', start, 'stop=', stop,
                        'now=', now, 'eventId=', eventId)
        return None, None
    hasSend = official_dao.getOfficialPushRecord(userId, gameId)
    if not hasSend:
        return 1, 'ok'
    hasSendAttrNames = [json.loads(i).keys()[0] for i in hasSend]
    hasSendTimes = [json.loads(i).values()[0] for i in hasSend]
    if not pktimestamp.is_same_day(timeStamp, hasSendTimes[-1]):
        return 1, None
    if timeStamp - hasSendTimes[-1] < 5 * 60:
        return None, 'ok'
    if len(hasSend) < 5:
        if eventId not in hasSendAttrNames:
            return 1, 'ok'
        if eventId in [PROMOTE, WITHDRAW, RED_ENVELOPE
                       ] and hasSendAttrNames.count(eventId) == 1:
            return 1, 'ok'
    return None, None
Example #2
0
def _checkSendCondition(userId, gameId, eventId, timeStamp, conf):
    startTime = configure.getGameJson(DIZHU_GAMEID, 'official.message',
                                      {}).get('startTime')
    stopTime = configure.getGameJson(DIZHU_GAMEID, 'official.message',
                                     {}).get('stopTime')
    start = datetime.datetime.strptime(startTime, "%H:%M").time()
    stop = datetime.datetime.strptime(stopTime, "%H:%M").time()
    now = datetime.datetime.now().time()
    if start >= stop or now < start or now > stop:
        if ftlog.is_debug():
            ftlog.debug('wx_official._checkSendCondition', 'userId=', userId,
                        'gameId=', gameId, 'start=', start, 'stop=', stop,
                        'now=', now, 'eventId=', eventId)
        return None, None
    hasSend = official_dao.getOfficialPushRecord(userId, gameId)
    if not hasSend:
        return 1, 'ok'
    hasSendAttrNames = [json.loads(i).keys()[0] for i in hasSend]
    hasSendTimes = [json.loads(i).values()[0] for i in hasSend]
    if not pktimestamp.is_same_day(timeStamp, hasSendTimes[-1]):
        return 1, None
    if timeStamp - hasSendTimes[-1] < conf.get('timeInterval'):
        return None, None
    if len(hasSend) < conf.get('dayTimes'):
        if hasSendAttrNames.count(
                eventId) < conf['templates'][eventId]['count']:
            return 1, 'ok'
    return None, None
Example #3
0
def getShareDownloadUrl(gameId, userId, source):
    clientId = sessiondata.getClientId(userId)
    ok, clientOs, cid, special, mc, sc = parseClientIdForDL(clientId)
    if not ok:
        ftlog.warn("getShareDownloadUrl|parseClientId|error", gameId, userId,
                   source, cid, special, mc, sc)
        return

    channels = configure.getGameJson(HALL_GAMEID,
                                     "download").get("channels", {})
    channel = clientOs + '.' + special + '.' + mc + '.' + sc

    downloadurl = channels['default']
    if channel in channels:
        downloadurl = channels[channel]

    mix_domain = [
        "dspkm.cc", "lkxjv.cc", "qkpwdfo.cc", "sijas.cc", "023i.cc",
        "lkjsdf.cc", "vdlskm.cc", "iojpdvs.cc", "sdvnkl.cc", "owirhj.cc",
        "lvsdp.cc", "msvdkn.cc", "dvslkm.cc", "odnsvk.cc", "p0joefipq.cc",
        "mvsdpok.cc", "02r389u.cc", "sdlknv.cc", "sdfioj.cc", "klsdvm.cc"
    ]

    domainList = configure.getGameJson(HALL_GAMEID,
                                       "misc").get("mix_domain", mix_domain)
    replaceDict = {
        'mc': mc,
        'sc': sc,
        'cid': str(cid),
        'uid': userId,
        'mixDomain': genMixDomain(domainList)
    }
    downloadurl = strutil.replaceParams(downloadurl, replaceDict)
    parsedUrl = urlparse.urlparse(downloadurl)
    qparams = urlparse.parse_qs(parsedUrl.query) if parsedUrl.query else {}
    qparams = {k: v[0] for k, v in qparams.iteritems()}
    qparams.update({'source': source})

    results = {}
    results['action'] = 'geturl'
    results['downloadurl'] = urlparse.urlunparse(
        (parsedUrl[0], parsedUrl[1], parsedUrl[2], parsedUrl[3],
         urllib.urlencode(qparams), parsedUrl[5]))

    from freetime.entity.msg import MsgPack
    from poker.protocol import router
    mp = MsgPack()

    mp.setCmd('share_hall')
    mp.setResult('gameId', gameId)
    mp.setResult('userId', userId)
    mp.updateResult(results)
    router.sendToUser(mp, userId)
    if ftlog.is_debug():
        ftlog.debug("getShareDownloadUrl|", gameId, userId, results)
Example #4
0
def getNeiTuiGuangConf(clientId):
    templates = configure.getGameJson(HALL_GAMEID, 'neituiguang', {}, configure.DEFAULT_CLIENT_ID).get('templates', {})
    intClientId = pokerconf.clientIdToNumber(clientId)
    templateName = configure.getGameJson(HALL_GAMEID, 'neituiguang', {}, intClientId).get('template', '')
    if templateName:
        return templates.get(templateName, {})
    else:
        _, clientVer, _ = strutil.parseClientId(clientId)
        if clientVer >= 3.372:
            return templates.get('default_neituiguang_new', {})
        else:
            return templates.get('default_neituiguang_3_37', {})
Example #5
0
def getOnlineUserCountRate(clientId):
    gameId = strutil.getGameIdFromHallClientId(clientId)
    intClientidNum = pokerconf.clientIdToNumber(clientId)
    infos = configure.getGameJson(gameId, 'online.info', {}, intClientidNum)
    rate = infos.get('rate', None)
    if rate:
        return rate
    infos = configure.getGameJson(gameId, 'online.info', {}, 0)
    rate = infos.get('rate', None)
    if rate:
        return rate
    return 1
Example #6
0
def getOnlineUserCountRate(clientId):
    gameId = strutil.getGameIdFromHallClientId(clientId)
    intClientidNum = pokerconf.clientIdToNumber(clientId)
    infos = configure.getGameJson(gameId, 'online.info', {}, intClientidNum)
    rate = infos.get('rate', None)
    if rate:
        return rate
    infos = configure.getGameJson(gameId, 'online.info', {}, 0)
    rate = infos.get('rate', None)
    if rate:
        return rate
    return 1
Example #7
0
def makeBeforeActivityTodoTasks(gameId, userId, clientId):
    try:
        intClientId = pokerconf.clientIdToNumber(clientId)
        enable = pkconfigure.getGameJson(gameId, 'pop.activity', {},
                                         intClientId).get('enable', 0)
        if not enable:
            return None
        msg = pkconfigure.getGameJson(gameId, 'pop.activity', {},
                                      pkconfigure.DEFAULT_CLIENT_ID)
        if msg:
            return TodoTaskShowInfo(msg)
    except:
        ftlog.exception()
    return None
Example #8
0
def getNeiTuiGuangConf(clientId):
    templates = configure.getGameJson(HALL_GAMEID, 'neituiguang', {},
                                      configure.DEFAULT_CLIENT_ID).get(
                                          'templates', {})
    intClientId = pokerconf.clientIdToNumber(clientId)
    templateName = configure.getGameJson(HALL_GAMEID, 'neituiguang', {},
                                         intClientId).get('template', '')
    if templateName:
        return templates.get(templateName, {})
    else:
        _, clientVer, _ = strutil.parseClientId(clientId)
        if clientVer >= 3.372:
            return templates.get('default_neituiguang_new', {})
        else:
            return templates.get('default_neituiguang_3_37', {})
Example #9
0
def getAllTcDatas(moduleName):
    datas = {}
    for gid in pokerconf.getConfigGameIds():
        subdata = configure.getGameJson(gid, moduleName, {}, configure.CLIENT_ID_TEMPLATE)
        #         ftlog.debug('getAllTcDatas', gid, moduleName, subdata)
        for k, d in subdata.items():
            if not k in datas:
                if isinstance(d, dict):
                    datas[k] = {}
                else:
                    datas[k] = []

            if isinstance(d, dict):
                # check dict config
                for k1, d1 in d.items():
                    if k1 in datas[k]:
                        ftlog.debug('Notice ModuleName:', moduleName
                                    , ' Duplicated key:', k1
                                    , ' gameId:', gid
                                    , ' content:', d1)
                datas[k].update(d)
            elif isinstance(d, list):
                datas[k].extend(d)
            # try:
            #                     datas[k].sort(key=lambda x: x['name'])
            #                 except:
            #                     try:
            #                         datas[k].sort(key=lambda x: x['id'])
            #                     except:
            #                         pass
            else:
                datas[k] = d
                #     ftlog.debug('getAllTcDatas', 'all', moduleName, datas)
    return datas
Example #10
0
def getGameListTemplateName(clientId):
    intClientId = pokerconf.clientIdToNumber(clientId)
    ftlog.debug("intClientId:", intClientId)
    if intClientId == 0:
        return 'hall_game_default'
    template = configure.getGameJson(HALL_GAMEID, 'gamelist', {}, intClientId)
    return template.get('template', 'hall_game_default')
Example #11
0
def _reloadConf():
    global _scoreRankConf
    d = configure.getGameJson(DIZHU_GAMEID, 'score.ranklist', {}, 0)
    conf = ScoreRankConf().decodeFromDict(d)
    _scoreRankConf = conf
    ftlog.info('dizhu_score_ranking._reloadConf successed', 'rankIds=',
               _scoreRankConf.rankingDefineMap.keys())
Example #12
0
def get_room_other_config(gameId):
    """
    获取房间相关的其他配置
    """
    key = 'room.other'
    config = configure.getGameJson(gameId, key, {})
    return config
Example #13
0
def get_medal_ui_config(gameId):
    """ 获取medal的ui配置
    """
    key = 'ui.config'
    ui_config = configure.getGameJson(gameId, key,
                                      {}).get('medal.ui.config', {})
    return ui_config
    def reloadConf(self):
        taskKindMap = {}
        taskKindList = []
        acts = []

        conf = configure.getGameJson(HALL_GAMEID, 'red_packet_task', {})

        closed = conf.get('closed', 0)
        if not isinstance(closed, int) or closed not in (0, 1):
            raise TYBizConfException(conf, 'closed must be int in (0, 1)')

        for actD in conf.get('acts', []):
            act = RPAct().fromDict(actD)
            acts.append(act)

        for taskKindConf in conf.get('tasks', []):
            taskKind = RPTaskKind().decodeFromDict(taskKindConf)
            if taskKind.kindId in taskKindMap:
                raise TYBizConfException(
                    conf, 'Duplicate taskKind %s' % (taskKind.kindId))
            taskKindMap[taskKindConf['kindId']] = taskKind
            taskKindList.append(taskKind)

        self._unregisterEvents(self._taskKindList)
        self._registerEvents(taskKindList)

        self._taskKindList = taskKindList
        self._taskKindMap = taskKindMap
        self._acts = acts
        self._closed = closed

        ftlog.info('RPTaskSystem.reloadConf ok', 'closed=', self._closed,
                   'taskList=',
                   [taskKind.kindId for taskKind in self._taskKindList],
                   'acts=', [act.todotaskFac for act in self._acts])
Example #15
0
def getTableSmilesInfo(bigRoomId, vipLevel):
    infos = configure.getGameJson(DIZHU_GAMEID, 'table.smilies', {},
                                  configure.DEFAULT_CLIENT_ID)
    template = infos.get('rooms', {}).get(str(bigRoomId), '')
    ftlog.debug('bigRoomId=', bigRoomId, 'template=', template, 'infos=',
                infos)
    vips = getattr(infos, '_vips_', None)
    if not vips:
        vips = {}
        setattr(infos, '_vips_', vips)
        viplist = infos.get('vip_special', [])
        templates = infos.get('templates', {})
        for k, v in templates.items():
            vips[k] = [[0, strutil.cloneData(v)]]
            for x in viplist:
                level = x['level']
                rate = x['rate'] + 1
                v = strutil.cloneData(v)
                for _, sv in v.items():
                    sv['self_charm'] = int(sv['self_charm'] * rate)
                vips[k].append([level, v])
                ftlog.debug('vips[k][level]->', k, level, v)
            vips[k].sort(key=lambda x: x[0], reverse=True)

    ftlog.debug('vips=', vips)
    confs = vips.get(template)
    if not confs:
        return {}
    if vipLevel > 0:
        for conf in confs:
            if vipLevel >= conf[0]:
                return conf[1]
    return confs[-1][1]
Example #16
0
def getEmojiConf(gameId, bigRoomId, vipLevel):
    conf = configure.getGameJson(gameId, 'table.smilies', {},
                                 configure.DEFAULT_CLIENT_ID)
    templateName = conf.get('rooms', {}).get(str(bigRoomId))
    if ftlog.is_debug():
        ftlog.debug('emoji.getEmojiConf', 'gameId=', gameId, 'bigRoomId=',
                    bigRoomId, 'templateName=', templateName)
    template = conf.get('templates', {}).get(templateName)
    if not template:
        return None

    # 获取levelConf
    vipsConf = conf.get('vip_special')
    if not vipsConf:
        return template

    vipConf = None
    for item in vipsConf:
        if vipLevel > item['level']:
            vipConf = item
            break

    if not vipConf:
        return template

    template = strutil.cloneData(template)
    rate = vipConf['rate'] + 1
    for _, value in template.iteritems():
        value['self_charm'] *= rate
    return template
Example #17
0
def _loadGameConf(gameId):
    conf = configure.getGameJson(gameId, 'share3', {}, 0)
    if not conf:
        return None, None
    
    sharePointMap = {}
    sharePointGroupMap = {}
    
    for gp in conf.get('groups', []):
        sharePointGroup = SharePointGroup3().decodeFromDict(gp)
        if sharePointGroup.groupId in sharePointGroupMap:
            raise TYBizConfException(gp, 'Duplicate sharePointGroupId %s' % (sharePointGroup.groupId))
        sharePointGroupMap[sharePointGroup.groupId] = sharePointGroup

    if ftlog.is_debug():
        ftlog.debug('hall_share3._loadGameConf',
                    'gameId=', gameId,
                    'groupIds=', sharePointGroupMap.keys())

    for sp in conf.get('points', []):
        sharePoint = SharePoint3().decodeFromDict(sp)
        if sharePoint.pointId in sharePointMap:
            raise TYBizConfException(sp, 'Duplicate sharePointId %s' % (sharePoint.pointId))
        if sharePoint.groupId:
            group = sharePointGroupMap.get(sharePoint.groupId)
            if not group:
                raise TYBizConfException(sp, 'Not found groupId %s for sharePoint %s' % (sharePoint.groupId, sharePoint.pointId))
            sharePoint.group = group
        sharePointMap[sharePoint.pointId] = sharePoint
    
    return sharePointMap, sharePointGroupMap
Example #18
0
def getAllTcDatas(moduleName):
    datas = {}
    games = pokerconf.getConfigGameIds()

    for gid in games:
        subdata = configure.getGameJson(gid, moduleName, {},
                                        configure.CLIENT_ID_TEMPLATE)
        for k, d in subdata.items():
            if not k in datas:
                if isinstance(d, dict):
                    datas[k] = {}
                else:
                    datas[k] = []

            if isinstance(d, dict):
                # check dict config
                for k1, d1 in d.items():
                    if k1 in datas[k]:
                        ftlog.debug('Notice ModuleName:', moduleName,
                                    ' Duplicated key:', k1, ' gameId:', gid,
                                    ' content:', d1)
                datas[k].update(d)
            elif isinstance(d, list):
                datas[k].extend(d)
            # try:
            #                     datas[k].sort(key=lambda x: x['name'])
            #                 except:
            #                     try:
            #                         datas[k].sort(key=lambda x: x['id'])
            #                     except:
            #                         pass
            else:
                datas[k] = d
                #     ftlog.debug('getAllTcDatas', 'all', moduleName, datas)
    return datas
Example #19
0
def getLuckyChipByVip(userId, gameId):
    vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
    luckyChipsByVip = configure.getGameJson(gameId, 'lead_to_pay')['luckyChipsByVip']
    if vipLevel < len(luckyChipsByVip):
        return luckyChipsByVip[vipLevel]
    else:
        return luckyChipsByVip[-1]
Example #20
0
def checkReplayRankingPrizeTime():
    ''' 检测重放排行榜发奖有效期 '''
    conf = configure.getGameJson(DIZHU_GAMEID, 'replay', {}, configure.DEFAULT_CLIENT_ID)
    rankingPrizeDatetime = conf.get('rankingPrizeDatetime')
    if not rankingPrizeDatetime:
        if ftlog.is_debug():
            ftlog.debug('replay_ranking_prize_sender.checkReplayRankingPrizeTime:',
                        'rankingPrizeDatetime is None')
        return False
    prizeStartTimeStr = rankingPrizeDatetime.get('datetime_start')
    prizeEndTimeStr = rankingPrizeDatetime.get('datetime_end')
    if not prizeStartTimeStr or not prizeEndTimeStr:
        if ftlog.is_debug():
            ftlog.debug('replay_ranking_prize_sender.checkReplayRankingPrizeTime:',
                        'prizeStartTimeStr or prizeEndTimeStr is None')
        return False
    
    dateNow = datetime.now()
    dateStart = pktimestamp.parseTimeSecond(prizeStartTimeStr)
    dateEnd = pktimestamp.parseTimeSecond(prizeEndTimeStr)
    if ftlog.is_debug():
        ftlog.debug('replay_ranking_prize_sender.checkReplayRankingPrizeTime:',
                    'dateNow=', dateNow, 
                    'dateStart=', dateStart, 
                    'dateEnd=', dateEnd)
    return dateStart<=dateNow and dateNow<=dateEnd
Example #21
0
def get_room_other_config(gameId):
    """
    获取房间相关的其他配置
    """
    key = 'room.other'
    config = configure.getGameJson(gameId, key, {})
    return config
Example #22
0
def getRankingPrizeItemList():
    ''' 
    获得排行榜奖励对象列表list<TYRankingRankReward> 
    '''
    conf = configure.getGameJson(DIZHU_GAMEID, 'replay', {}, configure.DEFAULT_CLIENT_ID)
    rankingPrizeListConf = conf.get('rankingPrizeList', [])
    return [TYRankingRankReward.decodeFromDict(conf) for conf in rankingPrizeListConf]
Example #23
0
def _isfilterConditions_group1(userId, clientId):
    conf = configure.getGameJson(HALL_GAMEID, 'gamelistipfilter', {}, configure.DEFAULT_CLIENT_ID)

    ipstr = sessiondata.getClientIp(userId)
    if not iploc.isBjSzIp(ipstr):
        if _DEBUG:
            ftlog.debug('_isfilterConditions_group1', userId, ipstr, 'enableIpCheck !')

        adjustVIP = 0
        adjustPlayTime = 0
        group1_passVipLevel = conf.get('group1_passVipLevel', 0)
        if group1_passVipLevel > 0:
            vipLevel = _getVIpLevel(userId)
            if vipLevel >= group1_passVipLevel:
                if _DEBUG:
                    ftlog.debug('_isfilterConditions_group1', userId, vipLevel, group1_passVipLevel, 'group1_passVipLevel !')
                adjustVIP = 1

        group1_passTotalPlayTime = conf.get('group1_passTotalPlayTime', 0)
        if group1_passTotalPlayTime > 0:
            totalTime = _getPlayTimes(userId)
            if totalTime >= group1_passTotalPlayTime:
                if _DEBUG:
                    ftlog.debug('gamelistipfilter', userId, totalTime, group1_passTotalPlayTime, 'group1_passTotalPlayTime !')
                adjustPlayTime = 1

        return adjustVIP == 1 and adjustPlayTime == 1
    else:
        if _DEBUG:
                ftlog.debug('_isfilterConditions_group1 is in beijing or shenzhe!! userId = ', userId , 'enableIpCheck !')
        return 0
Example #24
0
    def doChooseRoom(self, userId, clientId):
        if self.gameId == 38:
            chooseRoomRatio = configure.getGameJson(
                self.gameId, "misc", {}).get("choose_room_ratio", 1.0)
            baseN = gdata.rooms().values(
            )[0].tableConf["maxSeatN"] * chooseRoomRatio
            candidateRooms = []
            if ftlog.is_debug():
                ftlog.debug("|roomIds:", gdata.rooms().keys(), caller=self)
            allPlayersN = 1
            for room in gdata.rooms().values():
                if not isinstance(room, TYVipRoom):
                    continue
                playersN = room.maptable.values()[0].playersNum
                allPlayersN += playersN
                candidateRooms.append([room.roomId, playersN])

            candidateRooms.sort(key=lambda x: x[0])  # 所有房间按roomId排序
            maxRoomIndex = int(math.ceil(allPlayersN / baseN))
            sortedCandidateRooms = sorted(candidateRooms[0:maxRoomIndex],
                                          key=lambda x: x[1])  # 前几个房间按人数排序
            if ftlog.is_debug():
                ftlog.info("doChooseRoom |allPlayersN, baseN, candidateRooms:",
                           allPlayersN,
                           baseN,
                           candidateRooms,
                           "|maxRoomIndex, sortedCandidateRooms:",
                           maxRoomIndex,
                           sortedCandidateRooms,
                           caller=self)
            return sortedCandidateRooms[0][0]
Example #25
0
def _reloadConf():
    global _conf
    confDict = configure.getGameJson(HALL_GAMEID, 'neituiguang2', {},
                                     configure.DEFAULT_CLIENT_ID)
    conf = NeituiguangConf().decodeFromDict(confDict)
    _conf = conf
    ftlog.debug('neiguituang._reloadConf conf=', confDict)
Example #26
0
    def getMatchCalendar(self):
        from poker.entity.configure import configure
        calendarConf = configure.getGameJson(DIZHU_GAMEID, 'match.calendar',
                                             {})
        if not calendarConf or calendarConf.get('closed', 0) == 1:
            return {'error': {'ec': -1, 'message': '页面不存在'}}
        from dizhu.servers.util.game_handler import GameTcpHandler
        calendarInfo = GameTcpHandler.buildCalendarInfo(calendarConf)

        shareInfo = []
        for match in calendarInfo['matches']:
            if match.get('shareFlag') == 1:
                shareInfo.append({
                    'name': match.get('name'),
                    'time': match.get('time'),
                    'rewardName': match.get('rewardName'),
                    'shareImgs': match.get('shareImgs', []),
                    'timeList': match.get('timeList', []),
                })

        mo = MsgPack()
        mo.setCmd('match_share')
        mo.setResult('action', 'share')
        mo.setResult('code', 0)
        mo.setResult('currentTime',
                     datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        mo.setResult('money', calendarInfo['moneyWeb'])
        mo.setResult('tomorrowReward', calendarInfo['dates'][1])
        mo.setResult('todayReward', calendarInfo['shareImgs'])
        mo.setResult('info', shareInfo)
        return mo
Example #27
0
def checkMatchSigninCond(userId, roomId):
    if userId <= 10000:
        # 机器人不检查
        return True, None

    matchCondConf = configure.getGameJson(DIZHU_GAMEID, 'bigmatch.filter', {})
    if not matchCondConf:
        if ftlog.is_debug():
            ftlog.debug(
                'dizhumatchcond.checkMatchSigninCond EmptyMatchCondConf roomId=',
                roomId, 'gameId=', DIZHU_GAMEID, 'userId=', userId,
                'matchCondConf=', matchCondConf)
        return True, None

    bigRoomId = gdata.getBigRoomId(roomId)
    condConf = matchCondConf.get(str(bigRoomId))

    if ftlog.is_debug():
        ftlog.debug('dizhumatchcond.checkMatchSigninCond roomId=', roomId,
                    'gameId=', DIZHU_GAMEID, 'userId=', userId, 'bigRoomId=',
                    bigRoomId, 'condConf=', condConf, 'matchCondConf=',
                    matchCondConf)

    if condConf:
        clientId = sessiondata.getClientId(userId)
        timestamp = pktimestamp.getCurrentTimestamp()
        cond = MatchCondition().decodeFromDict(condConf)
        if not cond.check(DIZHU_GAMEID, userId, clientId, timestamp):
            return False, cond
    return True, None
Example #28
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)
Example #29
0
def _get_conf_by_client_id(clientId):
    """通过client id获取代理代理商场配置"""
    int_client_id = pokerconf.clientIdToNumber(clientId)
    for conf in configure.getGameJson(HALL_GAMEID, "inviter_shop")['conf']:
        if int_client_id in conf['clientIds']:
            return conf
    return {}
Example #30
0
def getGameListTemplateName(clientId):
    intClientId = pokerconf.clientIdToNumber(clientId)
    ftlog.debug("intClientId:", intClientId)
    if intClientId == 0:
        return 'hall_game_default'
    template = configure.getGameJson(HALL_GAMEID, 'gamelist', {}, intClientId)
    return template.get('template', 'hall_game_default')
Example #31
0
def getTableRecordDownloadConf(gameId):
    conf = configure.getGameJson(GAME_ID, 'table_record', {})
    downloadUrl = conf.get("trDownloadPath", "")
    token = conf.get("trUploadKey", "")
    path = conf.get("trFilePath", "") + r"%d/" % gameId
    if ftlog.is_debug():
        ftlog.debug("|gameId, downloadUrl, token, path:", gameId, downloadUrl, token, path)
    return downloadUrl, token, path
Example #32
0
def getRoomLevelNameWithClientId(gameId, bigRoomId, clientId):
    """ 通过clientId获取游戏模板配置,没有返回游戏模板配置默认模板0.json """
    intClientidNum = pokerconf.clientIdToNumber(clientId)
    conf = configure.getGameJson(gameId, 'chargelead', None, intClientidNum)
    if conf:
        return conf.get(str(bigRoomId))
    else:
        return getRoomLevelName(gameId, bigRoomId)
Example #33
0
def getLuckyChipByVip(userId, gameId):
    vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
    luckyChipsByVip = configure.getGameJson(gameId,
                                            'lead_to_pay')['luckyChipsByVip']
    if vipLevel < len(luckyChipsByVip):
        return luckyChipsByVip[vipLevel]
    else:
        return luckyChipsByVip[-1]
Example #34
0
def getShareDownloadUrl(gameId, userId, source):
    clientId = sessiondata.getClientId(userId)
    ok, clientOs, cid, special, mc, sc = parseClientIdForDL(clientId)
    if not ok:
        ftlog.hinfo("getShareDownloadUrl|parseClientId|error", gameId, userId,
                    source, cid, special, mc, sc)
        return

    channels = configure.getGameJson(HALL_GAMEID,
                                     "download").get("channels", {})
    channel = clientOs + "." + special + "." + mc + "." + sc

    download = channels["default"]
    if channel in channels:
        download = channels[channel]

    mix_domain = [
        "dspkm.cc", "lkxjv.cc", "qkpwdfo.cc", "sijas.cc", "023i.cc",
        "lkjsdf.cc", "vdlskm.cc", "iojpdvs.cc", "sdvnkl.cc", "owirhj.cc",
        "lvsdp.cc", "msvdkn.cc", "dvslkm.cc", "odnsvk.cc", "p0joefipq.cc",
        "mvsdpok.cc", "02r389u.cc", "sdlknv.cc", "sdfioj.cc", "klsdvm.cc"
    ]

    domainList = configure.getGameJson(HALL_GAMEID,
                                       "misc").get("mix_domain", mix_domain)
    downloadurl = "http://" + HallShare.randomUrlPrefix(
    ) + "." + random.choice(
        domainList
    ) + download + "?" + "mc=" + mc + "&" + "sc=" + sc + "&" + "cid=" + str(
        cid) + "&" + "source=" + source

    results = {}
    results["action"] = "geturl"
    results["downloadurl"] = downloadurl

    from freetime.entity.msg import MsgPack
    from poker.protocol import router
    mp = MsgPack()

    mp.setCmd("share_hall")
    mp.setResult("gameId", gameId)
    mp.setResult("userId", userId)
    mp.updateResult(results)
    router.sendToUser(mp, userId)
    if ftlog.is_debug():
        ftlog.debug("getShareDownloadUrl|", gameId, userId, results)
Example #35
0
def _reloadConf():
    global _treasureChestTotalConf
    d = configure.getGameJson(DIZHU_GAMEID, 'treasure.chest', {}, 0)
    conf = TreasureChestTotalConf().fromDict(d)
    _treasureChestTotalConf = conf

    ftlog.info('treasure_chest._reloadConf succeed',
               '_treasureChestTotalConf=', _treasureChestTotalConf)
Example #36
0
def _reloadConf():
    global _endGameConf
    d = configure.getGameJson(DIZHU_GAMEID, 'endgame', {}, 0)
    conf = EndgameConf().decodeFromDict(d)
    _endGameConf = conf

    ftlog.info('endgame._reloadConf succeed',
               '_endGameConf=', _endGameConf)
Example #37
0
def _reloadConf():
    global _conf
    d = configure.getGameJson(HALL_GAMEID, 'tmpacts:buy_send_gift', {}, None)
    conf = Conf().decodeFromDict(d)
    _conf = conf
    ftlog.debug('buy_send_gift._reloadConf successed',
                'startTime=', conf.startDT.strftime('%Y-%m-%d %H:%M:%S'),
                'endTime=', conf.endDT.strftime('%Y-%m-%d %H:%M:%S'),
                'productIds=', [(productId, giftConf.gameIds) for productId, giftConf in _conf.giftMap.iteritems()])
Example #38
0
def getClientRankTemplateName(rankingKey, clientId):
    intClientId = pokerconf.clientIdToNumber(clientId)
    if intClientId == 0:
        return None

    rankingKeys = configure.getGameJson(HALL_GAMEID, 'ranking', {}, intClientId).get('rankingKeys')
    if not rankingKeys:
        return None

    return rankingKeys.get(rankingKey)
Example #39
0
def getMoreGames(clientId):
    gameId = strutil.getGameIdFromHallClientId(clientId)
    intClientId = pokerconf.clientIdToNumber(clientId)
    templates = configure.getGameTemplates(HALL_GAMEID, 'more.games', _adjustMoreGameTemplates)
    template = configure.getGameJson(gameId, 'more.games', {}, intClientId)
    template = template.get('template', 'default')
    info = templates.get(template)
    ftlog.debug('hallconf.getMoreGames clientId=', clientId,
                'gameId=', gameId,
                'intClientId=', intClientId,
                'template=', template,
                'info=', info)
    if info:
        return info
    return templates.get('default')
Example #40
0
    def unload(cls, gameId, handler_names=None):
        """卸载插件"""

        for name in handler_names:
            plugin = cls.get_plugin(name, gameId)
            if hasattr(plugin.module, "onUnload"):
                try:
                    plugin.module.onUnload(gameId)
                except Exception:
                    ftlog.error("TYPluginCenter.unload"
                                "|gameId, name:", gameId, name)
            del cls.plugins[gameId][name]

        handlers_config = configure.getGameJson(gameId, 'plugins', {})
        cls.buildEventMap(gameId, cls.plugins[gameId], handlers_config, cls.map_events[gameId])
Example #41
0
    def doChooseRoom(self, userId, clientId):
        if self.gameId == 38:
            chooseRoomRatio = configure.getGameJson(self.gameId, "misc", {}).get("choose_room_ratio", 1.0)
            baseN = gdata.rooms().values()[0].tableConf["maxSeatN"] * chooseRoomRatio
            candidateRooms = []
            if ftlog.is_debug():
                ftlog.debug("|roomIds:", gdata.rooms().keys(), caller=self)
            allPlayersN = 1
            for room in gdata.rooms().values():
                if not isinstance(room, TYVipRoom):
                    continue
                playersN = room.maptable.values()[0].playersNum
                allPlayersN += playersN
                candidateRooms.append([room.roomId, playersN])

            candidateRooms.sort(key=lambda x: x[0])  # 所有房间按roomId排序
            maxRoomIndex = int(math.ceil(allPlayersN / baseN))
            sortedCandidateRooms = sorted(candidateRooms[0:maxRoomIndex], key=lambda x: x[1])  # 前几个房间按人数排序
            if ftlog.is_debug():
                ftlog.info("doChooseRoom |allPlayersN, baseN, candidateRooms:", allPlayersN, baseN, candidateRooms,
                           "|maxRoomIndex, sortedCandidateRooms:",
                           maxRoomIndex, sortedCandidateRooms, caller=self)
            return sortedCandidateRooms[0][0]
Example #42
0
def getLoginRewardConf():
    conf = configure.getGameJson(HALL_GAMEID, 'login_reward', {}, configure.CLIENT_ID_TEMPLATE)
    return conf
Example #43
0
def get_medal_ui_config(gameId):
    """ 获取medal的ui配置
    """
    key = 'ui.config'
    ui_config = configure.getGameJson(gameId, key, {}).get('medal.ui.config', {})
    return ui_config
Example #44
0
def getTableRecordConfig():
    return configure.getGameJson(MAJIANG2, 'table_record', {})
Example #45
0
def getMajiangConf(gameId, mainKey, subKey, defaultRet = None):
    return configure.getGameJson(gameId, mainKey, {}).get(subKey, defaultRet)
Example #46
0
def getDomainTCConf():
    conf = configure.getGameJson(HALL_GAMEID, "domain", [], configure.CLIENT_ID_TEMPLATE)
    return conf
Example #47
0
def isEnableLogChatMsg(gameId):
    return configure.getGameJson(gameId, 'table_chat', {}).get('enableLogChatMsg', 1)
Example #48
0
def _reloadConf():
    global couponService
    conf = pkconfigure.getGameJson(HALL_GAMEID, 'coupon', {})
    couponService.reloadConf(conf)
Example #49
0
def getPublicConf(gameId, key):
    return configure.getGameJson(gameId, 'public', {}).get(key, {})
Example #50
0
def getFristRechargeVCConf():
    conf = configure.getGameJson(HALL_GAMEID, "first_recharge", {}, configure.CLIENT_ID_MATCHER)
    return conf
Example #51
0
 def doGetConfigOnline(self, gameId, clientIdNum, key):
     conf = configure.getGameJson(gameId, key, None, clientIdNum)
     return conf
Example #52
0
def getCustomRoomConf(gameId, key):
    return configure.getGameJson(gameId, 'custom_room', {}).get(key, {})
Example #53
0
    def reload(cls, gameId, handler_name='', handler_names=[], handlers_config=None):
        '''
        reload 某个 gameId 的插件

        @handlers_names: 指定要reload哪些plugin。不指定就reload所有(plugins越来越多,会比较慢)

        不管有没有指定 reload 哪些插件,都会重新 build 事件表。
        为什么不优化为只处理指定的plugins的事件?
        没有必要,性能瓶颈不在这,而且全部重新build一定不会出问题,而且的而且,那样做会增加复杂性。
        '''

        if not cls.needLoadPlugin():
            ftlog.info('reload >> |this type of server not need load plugin',
                       '|serverId, gameId:', gdata.serverId(), gameId, caller=cls)
            return

        if cls.isOtherGameServer(gameId):
            ftlog.info('reload >> |', 'do not reload in other game GR/GT',
                       '|serverId, gameId:', gdata.serverId(), gameId, caller=cls)
            return

        if not handlers_config:
            handlers_config = configure.getGameJson(gameId, 'plugins', {})
            if not handlers_config:
                return
                # handlers_config = dict([(hc['name'], hc) for hc in handlers_config])
        handlers_config_dict = dict([(hc['name'], hc) for hc in handlers_config['handlers']])
        ftlog.info('<< |', cls.plugins, handlers_config, caller=cls)

        if handler_name:
            handler_names = [handler_name]

        handlers_config_list = []  # to be reload
        cls.map_events[gameId] = {}  # 事件表
        if handler_names:
            for handler_name in handler_names:
                if handler_name in handlers_config_dict:
                    handlers_config_list.append(handlers_config_dict.get(handler_name))
                if handler_name in cls.plugins[gameId]:
                    del cls.plugins[gameId][handler_name]
        else:
            handlers_config_list = handlers_config['handlers']
            cls.plugins[gameId] = {}  # plugins 表

        # 先 reload modules
        plugins = cls.plugins[gameId]
        reloadPlugins = []
        for cfg in handlers_config_list:
            try:
                plugin = TYPlugin(gameId, cfg)
                if plugin.handlers:
                    plugins[cfg['name']] = plugin
                    reloadPlugins.append(plugin)
            except Exception as e:
                ftlog.exception(e)

        cls.buildEventMap(gameId, plugins, handlers_config, cls.map_events[gameId])

        ftlog.info("TYPluginCenter.reload | "
                   "reloadPlugins:", [plugin.name for plugin in reloadPlugins])

        # onReload 时可能会有阻塞操作而让出CPU, 这时有可能会产生新的事件
        # 如果在 onReload 后才 buildEventMap,则这个事件会丢(因为eventMap在build之前是空的)
        # 所以,把 onReload 移到 build Event Map 之后
        for plugin in reloadPlugins:
            try:
                plugin.onReload()
            except Exception as e:
                ftlog.exception(e)
Example #54
0
def _reloadConf():
    global _conf
    confDict = configure.getGameJson(HALL_GAMEID, 'neituiguang2', {}, configure.DEFAULT_CLIENT_ID)
    conf = NeituiguangConf().decodeFromDict(confDict)
    _conf = conf
    ftlog.debug('neiguituang._reloadConf conf=', confDict)
Example #55
0
def getThirdSDKSwitchConf():
    conf = configure.getGameJson(HALL_GAMEID, 'third_sdk_switch', {}, configure.DEFAULT_CLIENT_ID)
    return conf
Example #56
0
def getRenameConf():
    return configure.getGameJson(HALL_GAMEID, 'rename', {}, configure.DEFAULT_CLIENT_ID)
Example #57
0
def getClientRenameConf(clientId):
    intClientId = pokerconf.clientIdToNumber(clientId)
    if intClientId == 0:
        return {}
    return configure.getGameJson(HALL_GAMEID, 'rename', {}, intClientId)
Example #58
0
def _reloadConf():
    global _defaultTemplateMap
    # 0.json配置
    _defaultTemplateMap = configure.getGameJson(HALL_GAMEID, 'module_default')
    ftlog.debug('hall.module_default._reloadConf successed : ', _defaultTemplateMap)
Example #59
0
def getItemExchangeConf():
    conf = configure.getGameJson(HALL_GAMEID, 'item_exchange', {}, configure.CLIENT_ID_TEMPLATE)
    return conf