Beispiel #1
0
def sendWelcomeMail(userId):
    """
    发送欢迎邮件
    """
    message = None
    welcomeMailConfs = config.getCommonValueByKey("ignoreConf")
    clientId = util.getClientId(userId)
    ftlog.debug("sendWelcomeMail", userId, "clientId = ", clientId)
    lang = util.getLanguage(userId)
    rewards = config.getCommonValueByKey("welcomeMailRewards")
    for welcomeMailConf in welcomeMailConfs:
        if clientId in welcomeMailConf.get("clientIds", []):
            # 不可显示实物、人民币相关描述
            message = config.getMultiLangTextConf(
                "ID_CONFIG_BAN_ENTITY_WELCOME_MSG", lang=lang)
        else:
            # 可显示实物、人民币相关描述
            message = config.getMultiLangTextConf(
                "ID_CONFIG_ALLOW_ENTITY_WELCOME_MSG", lang=lang)
    if message:
        mail_system.sendSystemMail(userId,
                                   mail_system.MailRewardType.SystemReward,
                                   rewards,
                                   message=message,
                                   title=config.getMultiLangTextConf(
                                       "ID_MAIL_TITLE_HOT_WELCOME", lang=lang))
def getTreasureList(userId):
    """
    宝藏列表
    """
    treasures = []
    lang = util.getLanguage(userId)
    for kindId, treasureConf in config.getTreasureConf().iteritems():
        kindId = int(kindId)
        treasure = {}
        level, _ = getTreasureInfo(userId, kindId)
        treasure["kindId"] = kindId
        treasure["sortId"] = treasureConf["sortId"]
        treasure["name"] = config.getMultiLangTextConf(treasureConf["name"], lang=lang)
        treasure["desc"] = config.getMultiLangTextConf(treasureConf.get("desc"), lang=lang)
        treasure["level"] = level
        treasure["convert"] = treasureConf["convert"]
        treasures.append(treasure)

    def cmpSort(x, y):
        if x["level"] > y["level"]:
            return 1
        elif x["level"] < y["level"]:
            return -1
        else:
            if x["sortId"] < y["sortId"]:
                return 1
            else:
                return -1

    treasures.sort(cmp=cmpSort, reverse=True)
    return treasures
def getAllTabs(userId):
    """
    获取所有可以显示的排行榜
    """
    confs = []
    isVerLimit = util.isVersionLimit(userId)  # 是否是提审版本
    lang = util.getLanguage(userId)
    rankRewardConf = config.getAllRankConfs()
    # rankRewardConf = OrderedDict(sorted(rankRewardConf.iteritems(), key=lambda d: d[1]["order"]))
    # for rankType, conf in rankRewardConf.iteritems():
    #     if (isVerLimit is False or conf.get("reviewVerLimit", 0) == 0) and conf["visible"] and conf["showInCommon"]:
    #         confs.append({"rankType": int(rankType), "rankName": config.getMultiLangTextConf(str(conf["rankName"]), lang=lang)})
    for _tab in rankRewardConf.get("tabs"):
        ranks = []
        for _rankType in _tab["rankList"]:
            conf = rankRewardConf.get("ranks", {}).get(str(_rankType))
            if conf and (not isVerLimit or not conf.get("reviewVerLimit", 0)
                         ) and conf["visible"] and conf["showInCommon"]:
                ranks.append({
                    "rankType":
                    int(_rankType),
                    "rankName":
                    config.getMultiLangTextConf(str(conf["rankName"]),
                                                lang=lang)
                })
        if ranks:
            confs.append({
                "tabName":
                config.getMultiLangTextConf(str(_tab["tabName"]), lang=lang),
                "ranks":
                ranks
            })
    return confs
def provideFinishGrandPrixReward(userId):
    """
    完成大奖赛发放宝藏奖励到邮件
    """
    treasureConf = config.getTreasureConf(effectType=EffectType.MatchItemReward)
    if treasureConf:
        kindId = treasureConf["kindId"]
        level, levelConf = getTreasureInfo(userId, kindId)
        if not levelConf:
            return
        refreshTreasureState(userId, kindId)
        treasureData = getTreasure(userId, kindId)
        if treasureData[INDEX_FINISH_COUNT] >= treasureConf["limitCount"]:
            return
        rewards = []
        lang = util.getLanguage(userId)
        for _kindId, _count in levelConf.get("params", {}).iteritems():
            rewards.append({"name": int(_kindId), "count": _count})
        if rewards:
            treasureName = config.getMultiLangTextConf(treasureConf["name"], lang=lang)
            message = config.getMultiLangTextConf("ID_CONFIG_TREASURE_FINISH_GRAND_PRIX", lang=lang).format(level,
                                                                                                            treasureName)
            title = config.getMultiLangTextConf("ID_MAIL_TITLE_TREASURE_REWARD", lang=lang)
            mail_system.sendSystemMail(userId, mail_system.MailRewardType.TreasureReward, rewards, message, title)
            activeTreasure(userId, kindId, treasureData)
def provideTimeMatchRankReward(userId, roomId, rank, rankRewards):
    """
    回馈赛上榜发放宝藏奖励到邮件
    """
    treasureConf = config.getTreasureConf(effectType=EffectType.MatchRankRewardAdd)
    if treasureConf:
        kindId = treasureConf["kindId"]
        level, levelConf = getTreasureInfo(userId, kindId)
        if not levelConf:
            return
        refreshTreasureState(userId, kindId)
        treasureData = getTreasure(userId, kindId)
        if treasureData[INDEX_FINISH_COUNT] >= treasureConf["limitCount"]:
            return
        rewards = []
        lang = util.getLanguage(userId)
        ratio = levelConf["params"]["time_match"]
        for _reward in rankRewards:
            if _reward["name"] in config.BULLET_VALUE:
                name = config.BRONZE_BULLET_KINDID
                count = int(math.ceil(_reward["count"] * config.BULLET_VALUE[_reward["name"]] * ratio))
            else:
                name = _reward["name"]
                count = int(math.ceil(_reward["count"] * ratio))
            rewards.append({"name": name, "count": count})
        if rewards:
            matchName = config.getMultiLangTextConf(gdata.getRoomConfigure(roomId).get("name", ""), lang=lang)
            treasureName = config.getMultiLangTextConf(treasureConf["name"], lang=lang)
            message = config.getMultiLangTextConf("ID_CONFIG_TREASURE_TIME_MATCH_RANK", lang=lang)
            message = message.format(matchName, rank, level, treasureName)
            title = config.getMultiLangTextConf("ID_MAIL_TITLE_TREASURE_REWARD", lang=lang)
            mail_system.sendSystemMail(userId, mail_system.MailRewardType.TreasureReward, rewards, message, title)
            activeTreasure(userId, kindId, treasureData)
def sendGrandPrizeReward(roomId, tableId, userId, fId, coinCount, level,
                         seatId, fpMultiple):
    """
    发放巨奖奖励
    """
    try:
        rewards = [{"name": config.CHIP_KINDID, "count": coinCount}]
        room = gdata.rooms()[roomId]
        table = room.maptable[tableId]
        player = table.getPlayer(userId)

        msg = MsgPack()
        msg.setCmd("getGrandPrizeRewards")
        msg.setResult("gameId", FISH_GAMEID)
        msg.setResult("userId", userId)
        msg.setResult("fId", fId)
        msg.setResult("rewards", rewards)
        msg.setResult("level", level)
        msg.setResult("seatId", seatId)
        msg.setResult("fpMultiple", fpMultiple)
        GameMsg.sendMsg(msg, table.getBroadcastUids())

        if player:
            for bigRoomId in config.getGrandPrizeConf().get("roomIds", []):
                player.fireCost[str(bigRoomId)] = 0
            name = player.name
            player.addTableChip(coinCount, "BI_NFISH_GRAND_PRIZE")
            player.totalGainChip += coinCount
            # 深海巨奖触发幸运降临
            table.checkBigPrize(player,
                                coinCount // fpMultiple,
                                coinCount,
                                fpMultiple,
                                isGrandPriz=True)
        else:
            from poker.entity.dao import gamedata
            from newfish.entity.redis_keys import GameData
            fireCost = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                                GameData.fireCost, {})
            for bigRoomId in config.getGrandPrizeConf().get("roomIds", []):
                fireCost[str(bigRoomId)] = 0
            gamedata.setGameAttr(userId, FISH_GAMEID, GameData.fireCost,
                                 json.dumps(fireCost))
            name = util.getNickname(userId)
            util.addRewards(userId, rewards, "BI_NFISH_GRAND_PRIZE", roomId)

        leds = [
            "ID_LED_GRAND_PRIZE_1", "ID_LED_GRAND_PRIZE_2",
            "ID_LED_GRAND_PRIZE_3"
        ]
        if len(leds) > level >= 0:
            lang = util.getLanguage(userId)
            msg = config.getMultiLangTextConf(leds[level], lang=lang) % \
                  (name, config.getMultiLangTextConf(table.runConfig.title, lang=lang), util.formatScore(coinCount, lang=lang))
            user_rpc.sendLed(FISH_GAMEID, msg, id=leds[level], lang=lang)
    except Exception as e:
        ftlog.error("sendGrandPrizeReward", roomId, tableId, userId, fId,
                    coinCount, traceback.format_exc())
    return 0
def getReturnerMission(userId, clientId):
    """
    获取回归豪礼
    """
    timeLeft = 0
    currTime = int(time.time())
    returnerMission = getReturnerMissionData(userId)
    returnerMissionConf = config.getReturnerMissionConf()
    if returnerMission:
        # 获取回归豪礼结束倒计时
        expireDays = returnerMissionConf["expireDays"] * 24 * 3600
        endTime = returnerMission["lastActiveTime"] + expireDays
        timeLeft = max(endTime - currTime, 0)
    mo = MsgPack()
    mo.setCmd("returner_mission")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("timeLeft", timeLeft)
    if timeLeft > 0:
        # 是否首次登录弹出
        dayFirst = weakdata.incrDayFishData(userId, WeakData.returnerMission, 1)
        # 当前是激活后的第几个任务(按天处理)
        lastActiveTime = util.getDayStartTimestamp(returnerMission["lastActiveTime"])
        fewDays = (datetime.fromtimestamp(currTime) - datetime.fromtimestamp(lastActiveTime)).days + 1
        fewDays = max(1, min(fewDays, len(returnerMission["tasks"])))
        currentTaskId = returnerMissionConf["tasks"][fewDays - 1]["taskId"]
        lang = util.getLanguage(userId, clientId)
        # 任务数据
        tasks = buildTaskData(returnerMission, lang)
        mo.setResult("dayFirst", 1 if dayFirst == 1 else 0)
        mo.setResult("currentTaskId", currentTaskId)
        mo.setResult("rule", config.getMultiLangTextConf(returnerMissionConf["rule"], lang=lang))
        mo.setResult("tasks", tasks)
    router.sendToUser(mo, userId)
Beispiel #8
0
def _sendQuestFinished(userId, quest):
    """发送完成的每日任务"""
    level = util.getUserLevel(userId)
    if level < config.getCommonValueByKey("dailyQuestOpenLevel"):
        return
    lang = util.getLanguage(userId)
    mo = MsgPack()
    mo.setCmd("task")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("action", "finished")
    mo.setResult("taskId", quest["taskId"])
    # if quest["taskType"] == TaskType.CoinNum and quest["des"].find("%s") >= 0:
    #    des = quest["des"] % util.formatScore(quest["targetsNum"])
    # elif quest["des"].find("%d") >= 0:
    #    des = quest["des"] % quest["targetsNum"]
    # else:
    #    des = quest["des"]
    questDes = config.getMultiLangTextConf(quest["des"], lang=lang)
    if questDes.find("%s") >= 0:
        des = questDes % util.formatScore(quest["targetsNum"], lang=lang)
    elif questDes.find("%d") >= 0:
        des = questDes % quest["targetsNum"]
    elif questDes.count("{}") >= 2:
        des = questDes.format(quest["gunX"], quest["targetsNum"])
    else:
        des = questDes
    mo.setResult("des", des)
    router.sendToUser(mo, userId)
Beispiel #9
0
    def doFTEnter(self, ftId, userId, seatId):
        ftlog.info("FishFriendTable.doFTEnter", "tableId=", self.tableId,
                   "ftId=", ftId, "seatId=", seatId)
        lang = util.getLanguage(userId)
        if ftId != self.ftId:
            raise TYBizException(
                1,
                config.getMultiLangTextConf("ID_INPUT_ROOMID_ERROR_INFO",
                                            lang=lang))

        player = self.getPlayer(userId)
        if player and player.userId:
            self.sendFriendDetails(userId)
        else:
            if self._expiresTimer:  # 重置桌子超时计时器
                self._expiresTimer.cancel()
                self._expiresTimer = None
            self._expiresTimer = FTLoopTimer(self._tableExpiresTime, 0,
                                             self._tableExpires)
            self._expiresTimer.start()
            self._doTableQuickStart(userId, seatId)  # 用户进入
            self.sendFriendDetails(userId)  # 发送对战详情信息
            if userId != self.ftTable.userId:  # 记录参与者Id
                self.otherId = userId
                fight_history.addOneHistory(userId, self.ftTable.userId,
                                            fight_history.HistoryType.Enter,
                                            self.ftId,
                                            self.ftTable.fee)  # 进入房间记录
        return 0
def sendLuckyTreeInfo(userId, clientId):
    """
    发送免费金币摇钱树详情
    """
    isAppClient = util.isAppClient(userId)  # 判断是否为单包客户端
    luckyTreeConf = config.getLuckyTreeConf()
    accelerateTimes, rewardTs, copperCount = getRewardTsAndCopperCount(userId)
    vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
    vipLimit = luckyTreeConf.get("vipLimit")
    maxAcceleratetimes = luckyTreeConf.get("maxAcceleratetimes")
    state = 4
    if accelerateTimes < maxAcceleratetimes:
        if vipLevel >= vipLimit:
            state = 1
        else:
            state = 3 if isAppClient else 0
    else:
        state = 2
    message = MsgPack()
    message.setCmd("lucky_tree_info")
    message.setResult("gameId", FISH_GAMEID)
    message.setResult("userId", userId)
    message.setResult(
        "rule",
        config.getMultiLangTextConf(str(luckyTreeConf.get("rule")),
                                    lang=util.getLanguage(userId, clientId)))
    message.setResult("copperCount", copperCount)
    message.setResult("state", state)
    message.setResult("rewardTs", rewardTs)
    message.setResult("rewardCount", luckyTreeConf.get("rewardCount", 0))
    message.setResult("rewardsList", getAllRewardList())
    router.sendToUser(message, userId)
Beispiel #11
0
 def getTaskInfo(self):
     """
     获取返回给客户端的任务数据
     """
     progress = min(self.taskData["progress"], self.taskData["targetNum"])
     progress = int(progress) if progress - int(progress) == 0 else progress
     meProgress = progress - self.helpProgress
     meProgress = int(meProgress) if meProgress - int(meProgress) == 0 else meProgress
     taskInfo = {}
     taskInfo["taskId"] = self.taskConfig["taskId"]
     taskInfo["isLimitTime"] = self.isLimitTime()
     taskInfo["shareMode"] = 1   # 1 if not self.isLimitTime() or util.isLocationLimit(self.userId) else 0
     taskInfo["progress"] = [int(progress), int(meProgress), self.taskData["targetNum"]]
     taskInfo["state"] = self.taskData["state"]
     taskInfodescId = self.taskConfig["desc"]
     taskInfo["desc"] = config.getMultiLangTextConf(str(taskInfodescId), lang=util.getLanguage(self.userId))
     taskInfo["reward"] = self.taskConfig["rewards"]
     if self.receiveRewards:
         taskInfo["realReward"] = self.receiveRewards
     taskInfo["target"] = self.taskConfig["target"]
     taskInfo["suggestTarget"] = self.taskConfig["suggestTarget"]
     timeLeft = self.recordStartTime + self.taskInterval - int(time.time())
     taskInfo["timeLeft"] = timeLeft if timeLeft >= 0 else self.taskInterval
     taskInfo["timeLong"] = self.taskInterval
     taskInfo["failTimeConf"] = self.taskConfig["failTime"]
     taskInfo["failTime"] = self.taskData["failTime"]        # 失败次数
     taskInfo["isNextLimitTime"] = self.taskSystem.isNextLimitTime(self.getTaskId())
     taskInfo["model"] = TaskModel.Red if util.isNewbieRoom(self.player.table.typeName) and self.taskSystem.taskModel == TaskModel.Main else self.taskSystem.taskModel
     taskInfo["type"] = self.taskConfig["type"]
     if self.taskSystem.taskModel in [TaskModel.Red, TaskModel.Main]:
         taskInfo["index"] = self.taskSystem.allMainTaskIds.index(self.taskId)
     return taskInfo
Beispiel #12
0
 def doReturnFee(self, msg):
     """
     停服准备返还玩家报名费
     """
     # des = u"由于游戏维护导致您离开了比赛,特将此次报名费全额返还,请您查收!非常抱歉给您带来不便,祝您游戏愉快!"
     userList = msg.getParam("users")
     assert (isinstance(userList, list))
     for user in userList:
         userId = user.get("userId", 0)
         if userId <= config.ROBOT_MAX_USER_ID:
             continue
         lang = util.getLanguage(userId)
         des = config.getMultiLangTextConf("ID_DO_RETURN_FEE_MESSAGE",
                                           lang=lang)
         player = self.match.findPlayer(userId)
         if player and self.userFee.get(userId, None):
             fee = self.userFee.get(int(userId))
             rewardsList = []
             if fee:
                 rewardsList = util.convertToFishItems(fee)
             self._logger.debug("doReturnFee", "userId=", userId, "fee=",
                                rewardsList)
             self.match.matchUserIF.unlockUser(self.matchId, self.roomId,
                                               player.instId, userId)
             if rewardsList:
                 mail_system.sendSystemMail(
                     userId, mail_system.MailRewardType.SystemCompensate,
                     rewardsList, des)
 def sendPushCompleteInfo(self):
     """
     发送任务完成消息
     """
     message = MsgPack()
     message.setCmd("fishAchievementTaskComplete")
     message.setResult("gameId", FISH_GAMEID)
     message.setResult("userId", self.userId)
     taskInfo = {}
     taskInfo["taskId"] = self.taskConfig["Id"]
     taskInfo["type"] = self.taskConfig["type"]
     taskInfo["target"] = self.taskConfig["target"]["num"]
     taskInfo["state"] = TaskState.Complete
     descId = self.taskConfig["desc"]
     desc = config.getMultiLangTextConf(descId, lang=self.lang)
     if taskInfo["type"] == AchieveType.SkillUp:
         if desc.find("%d") >= 0:
             taskInfo["desc"] = desc % self.taskConfig["target"].get("condition", 0)
     else:
         if desc.find("%s") >= 0:
             taskInfo["desc"] = desc % util.formatScore(taskInfo["target"], lang=self.lang)
         elif desc.find("%d") >= 0:
             taskInfo["desc"] = desc % taskInfo["target"]
     message.setResult("result", taskInfo)
     router.sendToUser(message, self.userId)
Beispiel #14
0
 def sendTideTaskStartInfo(self, userId, timeLeft):
     """
     发送限时任务开始消息
     :param userId: 玩家Id
     :param timeLeft: 剩余时间
     """
     userData = self.usersData.get(userId, {})
     task = userData.get("task")
     if userData and task:
         msg = MsgPack()
         msg.setCmd("tide_task")
         msg.setResult("gameId", FISH_GAMEID)
         msg.setResult("userId", userId)
         msg.setResult("action", "start")
         msg.setResult("taskId", task["taskId"])
         desc = config.getMultiLangTextConf(str(task["desc"]),
                                            lang=util.getLanguage(userId))
         if desc.find("%d") >= 0:
             if task["taskType"] == 1:
                 desc = desc % (task["targets"].get(
                     "number", 0), task["targets"].get("target"))
             elif task["taskType"] == 2:
                 desc = desc % (task["targets"].get("number"))
             elif task["taskType"] == 3:
                 desc = desc % (task["targets"].get("number"))
         msg.setResult("desc", desc)
         msg.setResult("timeLeft", timeLeft)
         msg.setResult("timeLong", task["timeLong"])
         msg.setResult("taskType", task["taskType"])
         msg.setResult("rewardType", userData["rewardType"])
         msg.setResult("targets", task["targets"])
         msg.setResult("rewards", task["rewards"])
         GameMsg.sendMsg(msg, userId)
Beispiel #15
0
 def sendNcmpttTaskStartInfo(self, userId, timeLeft):
     """
     发送限时任务开始消息
     :param userId: 玩家Id
     :param timeLeft: 剩余时间
     """
     userData = self.usersData.get(userId, {})
     task = userData.get("task")
     if userData and task:
         msg = MsgPack()
         msg.setCmd("ncmptt_task")
         msg.setResult("gameId", FISH_GAMEID)
         msg.setResult("userId", userId)
         msg.setResult("action", "start")
         msg.setResult("taskId", task["taskId"])
         desc = config.getMultiLangTextConf(str(task["desc"]),
                                            lang=util.getLanguage(userId))
         if desc.find("%d") >= 0:
             desc = desc % (task["targets"].get("target1")
                            or task["targets"].get("number1", 0))
         msg.setResult("desc", desc)
         msg.setResult("timeLeft", timeLeft)
         msg.setResult("timeLong", task["timeLong"])
         msg.setResult("taskType", task["taskType"])
         msg.setResult("rewardType", userData["rewardType"])
         msg.setResult("targets", task["targets"])
         msg.setResult("reward", {"name": task["chestReward"], "count": 1})
         GameMsg.sendMsg(msg, userId)
Beispiel #16
0
def _sendMailBySender(senderUserId, receiverUserId, type, reward=None, desc=None, title=None):
    """
    添加邮件到发件人发件箱
    :param senderUserId: 发件人
    :param receiverUserId: 收件人
    :param type: 邮件类型
    :param reward: 附件奖励
    :param desc: 邮件内容
    :param title: 标题
    """
    curTime = int(time.time())
    desc = desc or ""
    reward = reward or []
    title = title or ""
    mailOutId = gamedata.incrGameAttr(senderUserId, FISH_GAMEID, GameData.outMailId, 1)
    mailOutInfos = gamedata.getGameAttrJson(senderUserId, FISH_GAMEID, GameData.outMailInfos, [])
    receiverUserName = util.getNickname(receiverUserId)
    mailOutInfos.insert(0, {
        "id": mailOutId,
        "userId": receiverUserId,
        "time": curTime,
        "name": receiverUserName,
        "reward": reward,
        "type": type,
        "desc": desc,
        "title": title
    })
    mailOutInfos = _removeOutMailExpData(mailOutInfos, MAX_OUT_MAIL_COUNT)
    gamedata.setGameAttr(senderUserId, FISH_GAMEID, GameData.outMailInfos, json.dumps(mailOutInfos))
    if type == MailRewardType.Present:
        lang = util.getLanguage(senderUserId)
        message = config.getMultiLangTextConf("ID_PRESENT_TO_OTHER_MSG", lang=lang)
        message = message.format(receiverUserName, receiverUserId, util.buildRewardsDesc(reward, lang))
        GameMsg.sendPrivate(FISH_GAMEID, senderUserId, 0, message)
Beispiel #17
0
def sendGameplayInfo(roomId, userId, clientId, mode):
    """
    发送玩法相关信息
    """
    bigRoomId, _ = util.getBigRoomId(roomId)
    key = "%s_%d" % (bigRoomId, mode)
    lang = util.getLanguage(userId, clientId)
    conf = config.getSuperBossCommonConf()
    tabs = conf.get(str(key), {}).get("tabs", [])
    tabs = [{
        "title": config.getMultiLangTextConf(v["title"], lang=lang),
        "data": v["data"],
        "param": v.get("param", 0)
    } for v in tabs]
    mo = MsgPack()
    mo.setCmd("superboss_gameplay_info")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("roomId", roomId)
    mo.setResult("mode", mode)
    mo.setResult("tabs", tabs)
    router.sendToUser(mo, userId)
    checkModuleTip(bigRoomId, userId, mode)
    if ftlog.is_debug():
        ftlog.debug("gameplay, userId =", userId, "mo =", mo)
Beispiel #18
0
def vipAutoSupplyPerDay(userId):
    """
    vip每日自动补足
    """
    vipLevel = hallvip.userVipSystem.getVipInfo(userId).get("level", 0)
    key = GameData.autoSupplyKey % config.CHIP_KINDID
    autoSupplyCount = config.getVipConf(vipLevel).get(key, 0)
    chips = userchip.getUserChipAll(userId)
    if autoSupplyCount >= 10000 and chips < autoSupplyCount and weakdata.getDayFishData(
            userId, key, 0) == 0:
        weakdata.incrDayFishData(userId, key, 1)
        lang = util.getLanguage(userId)
        rewards = [{
            "name": config.CHIP_KINDID,
            "count": (autoSupplyCount - chips)
        }]
        message = config.getMultiLangTextConf(
            "ID_VIP_AUTO_SUPPLY_PER_DAY",
            lang=lang) % (autoSupplyCount / 10000)
        mail_system.sendSystemMail(userId,
                                   mail_system.MailRewardType.SystemReward,
                                   rewards, message)
    if ftlog.is_debug():
        ftlog.debug("vipAutoSupplyPerDay", userId, vipLevel, autoSupplyCount,
                    chips, key, autoSupplyCount - chips)
Beispiel #19
0
def getGiftDetail(giftConf, hasBought, enableDayIdx, lang):
    """获取礼包的详细信息"""
    gift = {}
    gift["giftId"] = giftConf["giftId"]
    # gift["giftName"] = giftConf["giftName"]
    gift["giftName"] = config.getMultiLangTextConf(giftConf["giftName"],
                                                   lang=lang)
    gift["productId"] = giftConf["productId"]
    gift["available"] = 0
    gift["price"] = giftConf["price"]
    gift["price_direct"] = giftConf.get("price_direct", 0)
    gift["price_diamond"] = giftConf.get("price_diamond", 0)
    gift["buyType"] = giftConf["buyType"]
    gift["otherBuyType"] = giftConf.get("otherBuyType", {})
    gift["otherProductInfo"] = {}
    # 特殊处理代购券商品数据
    from newfish.entity import store
    # gift["otherProductInfo"][BT_VOUCHER] = store.getVoucherProduct(gift["otherBuyType"])
    gift["otherProductInfo"] = store.getOtherBuyProduct(
        giftConf.get("otherBuyType", {}), giftConf["buyType"])
    gift["items"] = []
    for item in giftConf["giftInfo"]:
        newItems = []
        for v in item["items"]:
            newVal = config.rwcopy(v)
            if util.isChestRewardId(v["itemId"]):
                newVal["info"] = chest_system.getChestInfo(v["itemId"])
            newItems.append(newVal)
        gift["items"].append({item["day_idx"] + 1: newItems})
    gift["hasBought"] = hasBought
    gift["enableDayIdx"] = enableDayIdx
    return gift
Beispiel #20
0
 def getTimeDescStr(self, timeStr):
     """
     获取活动时间描述文本
     """
     intTime = util.getTimestampFromStr(timeStr)
     return util.timestampToStr(
         intTime,
         config.getMultiLangTextConf("ID_FORMAT_DATE", lang=self.lang))
Beispiel #21
0
def getLevelFundsData(userId, clientId, mode):
    """
    获取成长基金数据
    """
    message = MsgPack()
    message.setCmd("levelFundsData")
    message.setResult("gameId", config.FISH_GAMEID)
    message.setResult("userId", userId)
    if mode == -1:
        show = []
        for m in [config.CLASSIC_MODE, config.MULTIPLE_MODE]:
            isAllTaken = isShow(userId, clientId, m)[-1]
            if isAllTaken:
                show.append(1)
            else:
                show.append(0)
        message.setResult("show", show)
        message.setResult("mode", mode)
        router.sendToUser(message, userId)
        return
    if mode == 1:
        module_tip.resetModuleTipEvent(userId, "levelfundsNew")
    else:
        module_tip.resetModuleTipEvent(userId, "levelfunds")
    userLv, funds, userIdxs, lf_funds, lf_rewards, isAllTaken = isShow(userId, clientId, mode)
    message.setResult("level", userLv)
    fundsList = []
    addTipPIds = []
    isIn, roomId, _, _ = util.isInFishTable(userId)
    if isIn and not isAllTaken and util.isFinishAllNewbieTask(userId):
        for idx in userIdxs:
            productConf = funds[idx - 1]
            _funds = {}
            productId = productConf.get("productId")
            _funds["Id"] = productId
            _funds["state"] = 1 if idx in lf_funds else 0
            _funds["title"] = productConf.get("title")
            _funds["name"] = config.getMultiLangTextConf(productConf.get("name"), lang=util.getLanguage(userId))
            _funds["price_direct"] = productConf.get("price_direct")
            _funds["price_diamond"] = productConf.get("price_diamond")
            _funds["buyType"] = productConf.get("buyType")
            _funds["otherBuyType"] = productConf.get("otherBuyType")
            from newfish.entity import store
            _funds["otherProductInfo"] = store.getOtherBuyProduct(productConf.get("otherBuyType"), productConf.get("buyType"))
            hasTip, _funds["rewardsState"] = _getLevelFundsRewardState(userId, clientId, idx, mode, lf_rewards, lf_funds)
            if hasTip:
                addTipPIds.append(productId)
            fundsList.append(_funds)
    message.setResult("fundsList", fundsList)
    message.setResult("mode", mode)
    router.sendToUser(message, userId)
    if addTipPIds:
        if ftlog.is_debug():
            ftlog.debug("getLevelFundsData", mode)
        if mode == 1:
            module_tip.addModuleTipEvent(userId, "levelfundsNew", addTipPIds)
        else:
            module_tip.addModuleTipEvent(userId, "levelfunds", addTipPIds)
Beispiel #22
0
def _triggerTYOpenItemEvent(event):
    userId = event.userId
    itemKind = event.item.itemKind
    lang = util.getLanguage(userId)
    for key, value in config.getChestConf().iteritems():
        if value["kindId"] == itemKind.kindId:
            from hall.entity import halluser
            from hall.entity.todotask import TodoTaskShowInfo, TodoTaskHelper
            from newfish.entity import mail_system
            message = config.getMultiLangTextConf("ID_OPEN_ITEM_GET_REWARD_MSG", lang=lang) % value["name"]
            GameMsg.sendPrivate(FISH_GAMEID, userId, 0, message)
            todoTask = TodoTaskShowInfo(message)
            TodoTaskHelper.sendTodoTask(FISH_GAMEID, userId, todoTask)
            halluser.ensureGameDataExists(userId, FISH_GAMEID, util.getClientId(userId))
            message = config.getMultiLangTextConf("ID_USE_ITEM_GET_REWARD_MSG", lang=lang).format(itemKind.displayName, value["name"])
            rewards = [{"name": value["chestId"], "count": 1}]
            mail_system.sendSystemMail(userId, mail_system.MailRewardType.ChestReward, rewards, message)
            break
 def doGiveup(self, userId):
     if self._logger.isDebug():
         self._logger.debug("doGiveup", "userId=", userId)
     mo = MsgPack()
     mo.setCmd("m_giveup")
     mo.setResult("gameId", self.gameId)
     mo.setResult("roomId", self.roomId)
     mo.setResult("userId", userId)
     lang = util.getLanguage(userId)
     try:
         if self.match.giveup(userId):
             mo.setResult("giveup", 1)
         else:
             # mo.setResult("error", {"code": -1, "info": "不能退出比赛"})
             mo.setResult("error", {"code": -1, "info": config.getMultiLangTextConf("ID_MATCH_FORBID_GIVE_UP", lang=lang)})
     except:
         mo.setResult("error", {"code": -1, "info": config.getMultiLangTextConf("ID_MATCH_FORBID_GIVE_UP", lang=lang)})
     router.sendToUser(mo, userId)
Beispiel #24
0
 def getCurrentGiftConf(self):
     """
     获取当前可显示礼包的配置
     """
     isIn, roomId, _, _ = util.isInFishTable(self.userId)
     if not isIn:
         return [], ""
     mode = util.getGiftDTestMode(self.userId)
     fishPool = util.getFishPoolByBigRoomId(util.getBigRoomId(roomId)[0])
     grade, nextGrade = self._getGrade(fishPool)  # 获取礼包档位
     giftAbcTestConf = config.getGiftAbcTestConf(self.clientId)
     giftListConf = giftAbcTestConf.get("data", {}).get(
         str(fishPool), {}).get(grade, {}).get("giftList",
                                               {}).get(mode, [])
     nextGiftListConf = giftAbcTestConf.get("data", {}).get(
         str(fishPool), {}).get(nextGrade, {}).get("giftList",
                                                   {}).get(mode, [])
     buyTimes = self._getBuyTimes(fishPool)
     recommonGift = []
     # 当前房间可以使用的破产礼包列表.
     for idx, giftGroup in enumerate(zip(giftListConf, nextGiftListConf)):
         if not set(self.availableGift) & set(giftGroup):  # 优先展示可领取的礼包
             continue
         if buyTimes - 1 != idx:
             continue
         for giftId in giftGroup:
             giftConf = giftAbcTestConf.get("gift", {}).get(str(giftId))
             if not giftConf:
                 continue
             recommonGift.append(giftConf)
     if ftlog.is_debug():
         ftlog.debug("BankruptGift_getCurrentGiftConf", fishPool,
                     giftListConf, nextGiftListConf, grade, nextGrade,
                     recommonGift)
     # 没有可领取礼包则按照已购买次数显示礼包.
     if not recommonGift:
         if 0 <= buyTimes < len(giftListConf):
             listConf2 = giftAbcTestConf.get("data", {}).get(
                 str(fishPool),
                 {}).get(nextGrade, {}).get("giftList", {}).get(mode, [])
             giftId1, giftId2 = giftListConf[buyTimes], listConf2[buyTimes]
             recommonGift = [
                 giftAbcTestConf.get("gift", {}).get(str(giftId1)),
                 giftAbcTestConf.get("gift", {}).get(str(giftId2))
             ]
     lang = util.getLanguage(self.userId, self.clientId)
     remainTimes = max(0, len(giftListConf) - buyTimes)
     if recommonGift:
         gamedata.setGameAttr(self.userId, FISH_GAMEID,
                              GameData.bankruptGiftInfo,
                              json.dumps([fishPool, grade, nextGrade]))
         tip = config.getMultiLangTextConf("ID_BANKRUPT_GIFT_TIP",
                                           lang=lang).format(remainTimes)
     else:
         tip = ""
     return recommonGift, tip
Beispiel #25
0
 def getButtonInfo(self):
     """
     当前按钮数据
     """
     tasks = self._getTaskData()
     if self.isExpireTime() or tasks is None:
         return None, None
     ac_config = {}
     ac_config["Id"] = self.activityConfig["Id"]
     ac_config["name"] = config.getMultiLangTextConf(
         self.activityConfig["name"], lang=self.lang)
     ac_config["type"] = self.activityConfig["type"]
     ac_config["tabType"] = self.activityConfig["tabType"]
     ac_config["tabName"] = config.getMultiLangTextConf(
         self.activityConfig["tabName"], lang=self.lang)
     ac_config["order"] = self.activityConfig["order"]
     ac_config["read"] = self.activityData["read"]
     ac_config["activityTag"] = self.activityConfig["activityTag"]
     return ac_config, tasks
Beispiel #26
0
def sendVersionUpdateTipsMsg(userId, clientId, clientVersion):
    """
    发送版本更新提示消息
    """
    clientIdNum = util.getClientIdNum(userId, clientId)
    versionUpdateConf = config.getPublic("versionUpdateConf", {}).get(str(clientIdNum), {})
    for version in sorted(versionUpdateConf.keys()):
        if StrictVersion(str(clientVersion)) < StrictVersion(str(version)):
            lang = util.getLanguage(userId, clientId)
            conf = versionUpdateConf[version]
            mo = MsgPack()
            mo.setCmd("fishTips")
            mo.setResult("gameId", FISH_GAMEID)
            mo.setResult("info", config.getMultiLangTextConf(conf["info"], lang=lang))
            mo.setResult("desc", config.getMultiLangTextConf(conf["desc"], lang=lang))
            mo.setResult("type", conf["type"])
            mo.setResult("tipsUrl", conf["tipsUrl"])
            router.sendToUser(mo, userId)
            break
Beispiel #27
0
 def toString(cls, userId, reason):
     lang = util.getLanguage(userId)
     if reason == cls.USER_NOT_ENOUGH:
         # return u"由于参赛人数不足,比赛无法开启,报名费已返还,请期待下一场比赛吧"
         return config.getMultiLangTextConf(
             "ID_TAKE_MATCH_ERR_USER_NOT_ENOUGH", lang=lang)
     elif reason == cls.RESOURCE_NOT_ENOUGH:
         # return u"服务器开小差了,本场比赛临时被取消,报名费已返还,请期待下一场比赛吧"
         return config.getMultiLangTextConf(
             "ID_TAKE_MATCH_ERR_RES_NOT_ENOUGH", lang=lang)
     elif reason == cls.USER_LEAVE:
         # return u"由于您未在开赛前进入赛场等待,报名被取消了,报名费已自动退还,请关注下一场比赛吧"
         return config.getMultiLangTextConf("ID_TAKE_MATCH_ERR_USER_LEAVE",
                                            lang=lang)
     elif reason == cls.OVERTIME:
         # return u"比赛超时错误"
         return config.getMultiLangTextConf("ID_TAKE_MATCH_ERR_OVERTIME",
                                            lang=lang)
     return u""
Beispiel #28
0
def sendFishVipInfo(userId):
    """
    发送VIP特权信息
    """
    userVip = hallvip.userVipSystem.getUserVip(userId)
    vipLevelObj = userVip.vipLevel
    vipGiftBought = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                             GameData.vipGiftBought, [])
    lang = util.getLanguage(userId)
    levels = []
    for level in sorted(map(int, config.getVipConf().keys())):
        if level == 0 or (vipLevelObj.level <= 6 and level > 8):
            continue
        vipConf = config.getVipConf(level)
        vip = {}
        vip["level"] = vipConf["vipLv"]
        # vip["desc"] = vipConf["vipDesc"]
        vip["desc"] = config.getMultiLangTextConf(vipConf["vipDesc"],
                                                  lang=lang)
        vip["name"] = config.getMultiLangTextConf(vipConf["giftName"],
                                                  lang=lang)
        vip["productId"] = vipConf["productId"]
        vip["originalPrice"] = vipConf["originalPrice"]
        vip["price"] = vipConf["price"]
        vip["bought"] = 1 if vipConf["vipLv"] in vipGiftBought else 0
        vip["gift"] = vipConf["vipGift"]
        vip["canSetVipShow"] = vipConf.get("setVipShow", 0)
        levels.append(vip)
    totalExp = vipLevelObj.nextVipLevel.vipExp if vipLevelObj.nextVipLevel else vipLevelObj.vipExp
    mo = MsgPack()
    mo.setCmd("fish_vip_info")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("vipLevel", vipLevelObj.level)
    mo.setResult("exp", [userVip.vipExp, totalExp])
    mo.setResult("levels", levels)
    mo.setResult("showVip", util.isVipShow(userId))
    vipConf = config.getVipConf(vipLevelObj.level)
    mo.setResult("convert1137ToDRate", vipConf.get("convert1137ToDRate", 1))
    mo.setResult("convert1429ToDRate", vipConf.get("convert1429ToDRate", 0))
    mo.setResult("convert1430ToDRate", vipConf.get("convert1430ToDRate", 0))
    mo.setResult("convert1431ToDRate", vipConf.get("convert1431ToDRate", 0))
    router.sendToUser(mo, userId)
Beispiel #29
0
def notifyInspireInfo(roomId, teamId, ratio, remainTime, purchaserUid,
                      interval, lv):
    """
    通知购买鼓舞礼包
    """
    room = gdata.rooms()[roomId]
    ftlog.debug("notifyInspireInfo, ", roomId, teamId, ratio, remainTime,
                room.maptable.keys() if room else [])
    # for table in room.maptable.values():
    #     if table.playersNum:
    #         table.notifyInspireInfo(teamId, ratio, remainTime)
    name = util.getNickname(purchaserUid)
    avatar = userdata.getAttr(purchaserUid, "purl")
    ledTxt = {}
    from newfish.entity.fishactivity import competition_activity
    mo = MsgPack()
    mo.setCmd("comp_act_notify")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("teamId", teamId)
    mo.setResult("teamInspireBuf", (ratio, remainTime, lv))
    actState, actStateRemainTime = competition_activity._getCompStateAndRemainTime(
    )
    mo.setResult("actState", actState)
    mo.setResult("actStateRemainTime", actStateRemainTime)
    mo.setResult("avatar", avatar)
    mo.setResult("name", name)
    mo.setResult("interval", interval)
    for lang in util.getAllLanguage():
        teamName = config.getMultiLangTextConf("ID_COMPACT_TEAM_%d" %
                                               (teamId + 1),
                                               lang=lang)
        led = config.getMultiLangTextConf("ID_COMPACT_LED", lang=lang).format(
            name, teamName, interval)
        ledTxt[lang] = led
    for _uid in room._allPlayerDict.keys():
        if competition_activity._getCompTeamId(_uid) == teamId:
            lang = util.getLanguage(_uid)
            mo.setResult("led", ledTxt.get(lang, ""))
            GameMsg.sendMsg(mo, _uid)
            ftlog.debug("notifyInspireInfo, userId =", _uid, "teamId =",
                        teamId, "mo =", mo)
    return 1
 def sendGrandPrixInfo(self):
     """
     发送大奖赛信息 大奖赛相关信息(进入渔场后服务器主动推送)
     """
     if not grand_prix.isGrandPrixOpenTime():  # 是否为大奖赛开放时段 00:00 —— 23:00
         self._resetGrandPrixData()
         self._freeTimes = 0  # 免费次数
         weakdata.setDayFishData(self.userId,
                                 WeakData.grandPrix_getPointsInfo,
                                 json.dumps([]))
         weakdata.setDayFishData(self.userId, WeakData.grandPrix_freeTimes,
                                 self._freeTimes)
     if ftlog.is_debug():
         ftlog.debug("sendGrandPrixInfo", self.grandPrixStartTS,
                     self.isGrandPrixMode())
     signUpState = 1 if self.isGrandPrixMode() else 0  # 是否已经报名
     remainFreeTimes = config.getVipConf(self.vipLevel).get(
         "grandPrixFreeTimes", 0) - self._freeTimes  # 剩余免费次数
     openTime = "-".join(config.getGrandPrixConf("openTimeRange"))  # 时间范围
     mo = MsgPack()
     mo.setCmd("grand_prix_info")
     mo.setResult("gameId", FISH_GAMEID)
     mo.setResult("userId", self.userId)
     mo.setResult("seatId", self.seatId)
     mo.setResult("remainFreeTimes", remainFreeTimes)
     mo.setResult("fee", config.getGrandPrixConf("fee"))  # 报名费
     mo.setResult("openTime", openTime)  # 00:00 - 23:00
     mo.setResult(
         "isInOpenTime",
         1 if grand_prix.isGrandPrixOpenTime() else 0)  # 大奖在是否在开放时间段
     mo.setResult("signUpState", signUpState)  # 是否已报名大奖赛
     mo.setResult(
         "todayRankType",
         RankType.TodayGrandPrix)  # 今日榜Type,使用fish_ranking获取排行榜数据,下同
     mo.setResult("todayDate", util.timestampToStr(int(time.time()),
                                                   "%m/%d"))  # 今日榜时间
     mo.setResult("yesterdayRankType", RankType.LastGrandPrix)
     mo.setResult("yesterdayDate",
                  util.timestampToStr(int(time.time() - 86400), "%m/%d"))
     mo.setResult(
         "des",
         config.getMultiLangTextConf(
             config.getGrandPrixConf("info").get("des"),
             lang=self.lang))  # 每日积分超过2400送100珍珠,今日榜单每10分钟刷新1次,最终排名00:00公布
     mo.setResult("pointsInfo", grand_prix.getPointInfo(
         self.userId))  # 奖励积分 道具Id、道具数量、是否领取了奖励0|1
     mo.setResult("todayMaxPoints",
                  weakdata.getDayFishData(self.userId,
                                          WeakData.grandPrix_point,
                                          0))  # 今日最高积分
     GameMsg.sendMsg(mo, self.userId)
     if ftlog.is_debug():
         ftlog.debug("FishGrandPrixPlayer, userId =", self.userId, "mo =",
                     mo)