Example #1
0
def pay_handler(entityID, username, goodsid, amount=None):
    goodsid = str(goodsid)  # 必须是字符串
    label = username2label(username)
    sdktype = username2type(username)
    sdkconfigs = get_config(RechargeBySdktypeConfig).get(sdktype, [])
    labconfigs = get_config(RechargeByLabelConfig).get(label, [])
    configs = get_config(RechargeConfig)
    ids = {e.id for e in sdkconfigs} & {e.id for e in labconfigs}
    good = {configs[e].goodsid: configs[e] for e in ids}.get(goodsid)
    if not good:
        logger.error("error goodsid %r", goodsid)
        return
    p = g_entityManager.get_player(entityID)
    if p:
        level = p.level
        reward = give_goods(p, good, amount=amount)
        get_gold = reward.get("gold", 0)
    else:
        # patch 离线玩家,需要计算可获得金额
        p = Player.simple_load(
            entityID,
            ["userID", "level", "bought_recharges", "offline_recharges"])
        level = p.level
        if p.offline_recharges:
            p.offline_recharges.append([good.id, amount])
        else:
            p.offline_recharges = [[good.id, amount]]
        is_first = (good.id not in (p.bought_recharges or set())) \
            and (good.id not in ({i for i, j in p.offline_recharges} or set()))
        from reward.manager import open_reward, RewardType
        reward = open_reward(RewardType.Recharge, good, is_first, amount)
        rs = reward.apply_after()  # 仅计算可获金额,并不发货
        get_gold = rs.get("gold", 0)
        p.save()
    return {"username": username, "level": level, "get_gold": get_gold}
Example #2
0
def get_faction_info(factionID):
    faction = Faction.get(factionID)
    if not faction:
        return {}
    player = Player.simple_load(faction.leaderID, ['prototypeID', 'name'])
    return dict(
        factionID=factionID,
        name=faction.name,
        level=FactionRankRanking.get_score(faction.factionID) or 1,
        mcount=len(faction.memberset),
        acount=len(faction.applyset),
        totalfp=faction.totalfp,
        todayfp=faction.todayfp,
        rank=FactionRankRanking.get_rank(factionID),
        prototypeID=player.prototypeID,
        leader=player.name,
        createtime=faction.createtime,
        notice=faction.notice,
        mode=faction.mode,
        strengthen_hp_level=faction.strengthen_hp_level,
        strengthen_at_level=faction.strengthen_at_level,
        strengthen_ct_level=faction.strengthen_ct_level,
        strengthen_df_level=faction.strengthen_df_level,
        can_strengthen=get_config(CanStrengthenConfig)[1].can,
        leaderID=faction.leaderID,
        dflag=faction.dflag,
    )
Example #3
0
def quit_group(entityID, groupID):
    g = Group.simple_load(groupID, ["leaderID", "members", "invites"])
    if not g:
        return msgTips.FAIL_MSG_GROUP_NOT_IN_THIS
    g.members.load()
    g.invites.load()
    p = g_entityManager.get_player(entityID)
    if not p:
        p = Player.simple_load(entityID, ["groupID", "group_last_kicked_time"])
    if not p.groupID:
        return msgTips.FAIL_MSG_GROUP_HAS_NOT_JOINED  # "未加入同门了"
    if p.entityID not in g.members:
        return msgTips.FAIL_MSG_GROUP_NOT_IN_THIS
    del g.members[p.entityID]
    if p.entityID in g.invites:
        g.invites.remove(p.entityID)
    if p.entityID == g.leaderID:
        rest = sorted(g.members.items(), key=lambda v: v[1]["jointime"])
        if rest:
            new_leaderID, _ = rest[0]
            g.leaderID = new_leaderID
    recommend(groupID)
    g.save()
    p.groupID = 0
    now = int(time.time())
    p.group_last_kicked_time = now
    p.save()
    return SUCCESS
Example #4
0
def clean_faction(entityID):
    p = g_entityManager.get_player(entityID)
    if not p:
        p = Player.simple_load(entityID, ['factionID', 'applyFactions'])
    if p.factionID:
        faction = Faction.simple_load(p.factionID, ['memberset'])
        if faction:
            safe_remove(faction.memberset, p.entityID)
            faction.save()
        p.last_factionID = p.factionID
        gm_logger.info({
            'faction': {
                'entityID': p.entityID,
                'type': 'quit_faction',
                'factionID': p.factionID,
            }
        })
    p.factionID = 0
    p.fp = 0
    p.faction_name = ''
    p.faction_level = 0
    p.faction_is_leader = False
    p.applyFactions.clear()
    # p.applyFactionTime = 0
    p.save()
    if g_entityManager.get_player(entityID):
        p.sync()
Example #5
0
def join_group(entityID, groupID):
    now = int(time.time())
    p = g_entityManager.get_player(entityID)
    if not p:
        p = Player.simple_load(entityID, ["groupID", "group_last_kicked_time"])
    if p.groupID:
        return msgTips.FAIL_MSG_GROUP_ALREADY_JOINED
    if now < p.group_last_kicked_time + ONE_DAY:
        return msgTips.FAIL_MSG_GROUP_KICKED_RECENTLY
    g = Group.simple_load(groupID, ["members", "applys"])
    g.members.load()
    g.applys.load()
    if len(g.members) >= MAX_MEMBERS_COUNT:
        return msgTips.FAIL_MSG_GROUP_LIMITED_EXCEED
    if p.entityID in g.members:
        return msgTips.FAIL_MSG_GROUP_ALREADY_JOINED_THIS
    g.members[p.entityID] = {"jointime": now, "intimate": 0}
    if len(g.members) >= MAX_MEMBERS_COUNT:
        unrecommend(groupID)
        g.applys.clear()
    else:
        recommend(groupID)
        try:
            del g.applys[p.entityID]
        except KeyError:
            pass
    g.save()
    p.groupID = groupID
    p.save()
    return SUCCESS
Example #6
0
def blockdevice():
    entityID = int(request.POST.get("entityID") or 0)
    block = request.POST["block"] == 'True'
    if not entityID:
        return FAILURE
    from player.model import Player
    userID = Player.simple_load(entityID, ['userID']).userID
    if not userID:
        return FAILURE
    from user.model import User
    user = User.load(userID)
    imsi = user.imsi
    if not imsi:
        return FAILURE
    from session.regions import r_block_devices
    if block:
        r_block_devices.sadd(imsi)
    else:
        r_block_devices.srem(imsi)

    if block:
        for regionID, entityIDs in user.roles.items():
            for entityID in entityIDs:
                spawn(proxy_batch_call, 'chat.manager.clear_blocked_message',
                      regionID, entityID)

    return SUCCESS
Example #7
0
def blocktime():
    # userID = int(request.POST.get("userID") or 0)
    entityID = int(request.POST.get("entityID") or 0)
    blocktime = int(request.POST.get("blocktime") or 0)
    if not entityID:
        return FAILURE
    now = int(time.time())
    if blocktime and blocktime < now:
        return FAILURE
    from player.model import Player
    userID = Player.simple_load(entityID, ['userID']).userID
    if not userID:
        return FAILURE

    from user.model import User
    user = User.load(userID)
    user.blocktime = blocktime
    user.save()

    for regionID, entityIDs in user.roles.items():
        for entityID in entityIDs:
            spawn(proxy_batch_call, 'chat.manager.clear_blocked_message',
                  regionID, entityID)

    return SUCCESS
Example #8
0
def get_lineup_info(playerID, attrs, type=None):
    from player.model import Player
    from pet.model import Pet
    from entity.manager import g_entityManager
    if not type:
        type = LineupType.ATK
    p = g_entityManager.get_player(playerID)
    if p:
        pets = [p.pets.get(i, None) for i in p.lineups.get(type, [])]
    else:
        # p = Player.batch_load([playerID], ['lineups'])[0]  # FIXME
        p = Player.simple_load(playerID, ["entityID", "lineups"])
        p.lineups.load()
        if p:
            try:
                pets = Pet.batch_load(p.lineups.get(type, []),
                                      Pet.expend_fields(attrs))
            except IndexError:
                pets = []
    result = []
    for pos, pet in enumerate(pets):
        if not pet:
            continue
        info = {n: getattr(pet, n) for n in attrs}
        if type == LineupType.Daily:
            if info.get("daily_restHP", 0):
                info["restHP"] = info["daily_restHP"]
        info['posIndex'] = pos
        info['isTeamLeader'] = (pos == 0)
        result.append(info)
    return result
Example #9
0
def lock_device_and_skip_guide(entityID):
    from entity.manager import g_entityManager
    from player.model import Player, OfflineAttrType
    entityID = int(entityID)
    deviceID = request.POST.getone('deviceID', '')
    lock_level = int(request.POST.getone('lock_level', '50'))
    role = g_entityManager.get_player(entityID)
    if not role:
        Player.add_offline_attr(entityID,
                                Player.getAttributeIDByName('skip_guide'),
                                True, OfflineAttrType.Set)
        Player.add_offline_attr(entityID,
                                Player.getAttributeIDByName('lock_level'),
                                lock_level, OfflineAttrType.Set)
    else:
        role.skip_guide = True
        role.lock_level = lock_level
        role.save()
        role.sync()

    # lock device
    if not role:
        userID = Player.simple_load(entityID, ['userID']).userID
    else:
        userID = role.userID

    from user.model import User
    u = User.simple_load(userID, ['lock_device', 'imsi'])
    u.lock_device = deviceID or u.imsi
    u.save()
    return SUCCESS
Example #10
0
def loot_target(player, power, loot, count):
    dvalue = 100 + power * 0.06
    s, e = int(max(0, power - dvalue)), int(power + dvalue)
    samples = set(PlayerPowerRanking.get_range_by_score(s, e, count=16)) - set(
        [player.entityID])
    zombies = set(get_zombies_by_power(s, e, count=5))
    # s = max(player.level - 12, 1)
    # e = max(player.level - 6, 1)
    # samples = set(
    #     PlayerLevelRanking.get_range_by_score(
    #         s, e, count=16)
    # ) - set([player.entityID])
    # zombies = set(reduce(
    #     lambda x, y: x+y,
    #     [get_zombies_by_level(l)[:5]
    #         for l in range(s, e + 1)]))
    samples = samples.union(zombies)
    chosen = choice_one(list(samples))
    logger.debug("search targets is {}".format(samples))
    if not is_zombie(chosen):
        rest = search_targets_loot([chosen], loot)[0]
        p = Player.simple_load(chosen, "loot_protect_time")
        now = int(time.time())
        if PlayerLootLock.locked(chosen) or \
           now < p.loot_protect_time and rest < 50 and rest < count:
            chosen = choice_one(list(zombies))
    if not chosen:
        chosen = choice_one(list(get_zombies()))
    # # NOTE FIXME FOR DEBUG
    # chosen = player.entityID
    return get_opponent_detail(chosen)
Example #11
0
def discredit_offline(manager, entityID, current_floor):
    now = int(time.time())
    floor = manager.avail_floor(current_floor)

    attrs = ['climb_tower_accredit_earnings',
             'climb_tower_floor',
             'climb_tower_accredit_stash_time',
             'climb_tower_accredit_cd']
    p = Player.simple_load(entityID, Player.expend_fields(attrs))
    if p:
        if floor:
            value = p.climb_tower_accredit_earnings
            # 结束时间作为 score
            score = p.climb_tower_accredit_cd

            p.climb_tower_accredit_stash_earnings += value
            p.climb_tower_accredit_floor = floor
            p.climb_tower_accredit_stash_time = now
            # 取消当前层派驻
            manager.floors[current_floor].idx.unregister(p.entityID)
            manager.floors[floor].idx.register(p.entityID, score)

        else:
            p.climb_tower_accredit_cd = now
            manager.floors[current_floor].idx.unregister(p.entityID)
        p.save()
Example #12
0
File: rank.py Project: kimch2/x8623
def sync_rank_offline(entityID, history, fight=None):
    from player.model import Player
    FIGHT_HISTORY_LIMIT = 5
    pkey = make_key(Player.store_tag, entityID)
    history['ID'] = '%d:%d' % (history['time'], history['oppID'])
    if incr_score(entityID, history['score']):
        from chat.manager import on_news_pvp_first
        on_news_pvp_first(Player.simple_load(entityID, ["entityID", "name"]))
    Player.pool.execute('HINCRBY', pkey, 'rank_count', 1)
    Player.pool.execute("LPUSH", "rank_history_p{%d}" % entityID,
                        Player.fields['rank_history'].encoder(history))
    Player.pool.execute("LTRIM", "rank_history_p{%d}" % entityID, 0, 30)
    if fight:
        Player.pool.execute("HSET", "rank_fight_history_p{%d}" % entityID,
                            history['ID'], fight)
        keys = Player.pool.execute('HKEYS',
                                   "rank_fight_history_p{%d}" % entityID)
        if len(keys) > FIGHT_HISTORY_LIMIT:
            for key in sorted(keys)[:-FIGHT_HISTORY_LIMIT]:
                Player.pool.execute("HDEL",
                                    "rank_fight_history_p{%d}" % entityID, key)
    if history['isWin']:
        Player.pool.execute('HINCRBY', pkey, 'rank_win_count', 1)
    else:
        Player.pool.execute('HINCRBY', pkey, 'rank_passive_offline_count', 1)
    return 'FAILURE'
Example #13
0
 def alter_name(self, msgtype, body):
     limited, message = self.access_limited()
     if limited:
         return fail_msg(msgtype, reason=message)
     req = poem_pb.AlterNameRequest()
     req.ParseFromString(body)
     entityID = req.entityID
     if not entityID:
         user = User.load(self.userID)
         entityIDs = user.roles.get(settings.REGION['ID'])
         if len(entityIDs) > 1:
             return fail_msg(msgtype, reason="未指定角色")
         if entityIDs:
             entityID = entityIDs[0]
     if not PlayerDuplicateNamesIndexing.exists(entityID):
         return fail_msg(msgtype, reason="不可修改名称")
     session = SessionStore(get_session_pool(), str(req.verify_code))
     if not req.userID or session.uid != req.userID:
         return fail_msg(msgtype, reason="登录超时,请重试")
     name, error = validate_name(req.name)
     if error:
         return fail_msg(msgtype, error)
     # 名字去重复
     try:
         PlayernameIndexing.register(0, name)  # 占位
         p = Player.simple_load(entityID, ["name"])
         p.name = name
         p.save()
         PlayernameIndexing.pool.execute(
             'HSET', PlayernameIndexing.key, name, entityID)  # 更新
     except DuplicateIndexException:
         return fail_msg(msgtype, reason=_YYTEXT('该名称已存在'))
     PlayerDuplicateNamesIndexing.unregister(entityID)
     return success_msg(msgtype, '')
Example #14
0
File: city.py Project: kimch2/x8623
def city_send_mail_offline(entityID, title, content, rewards, key, ID):
    if not int(Player.pool.execute(
            "HSET", "city_rewards_recv_p{%d}" % entityID, key, "") or 0):
        return
    p = Player.simple_load(entityID, ['factionID'])
    rank = CityDungeonKillRanking.get_rank(p.factionID)
    content = content.format(rank)
    send_mail(entityID, title, content, addition=rewards, configID=ID)
Example #15
0
def allow_friend_offline(applyID, entityID):
    p = Player.simple_load(applyID, ["friendset", "level"])
    friend_max_count = get_friend_max_count(p.level)
    if len(p.friendset) >= friend_max_count:
        return False
    if len(p.friendset) + 1 >= friend_max_count:
        unrecommend(entityID)
    add_friend_offline(applyID, entityID)
    return True
Example #16
0
def sync_faction_offline(entityID, factionID, level, name):
    p = Player.simple_load(entityID,
                           ['factionID', 'faction_level', 'faction_name'])
    if p.factionID == factionID:
        p.faction_level = level
        p.faction_name = name
        p.save()
        p.sync()
    return True
Example #17
0
def remove_friend_offline(entityID, friendID):
    p = Player.simple_load(entityID, ["friendset"])
    try:
        p.friendset.remove(friendID)
        recommend(entityID)
    except KeyError:
        pass
    p.save()
    return True
Example #18
0
def sync_daily_rank_offline(entityID, history=None):
    p = Player.simple_load(entityID, [
        "daily_histories", "daily_history_flag"])
    p.daily_histories.load()
    if p:
        if history:
            p.daily_histories.appendleft(history)
            p.daily_histories.ltrim(0, MAX_HIST_LEN - 1)
            p.daily_history_flag = True
        p.save()
Example #19
0
def get_group_member_across_region(regionID, entityID):
    assert regionID == settings.REGION["ID"]
    p = Player.simple_load(entityID, ["name", "prototypeID", "groupID"])
    return {
        "name": p.name,
        "groupID": p.groupID,
        "regionID": regionID,
        "prototypeID": p.prototypeID,
        "entityID": entityID,
    }
Example #20
0
def ranking_send_mail_offline(entityID, title, content, rewards, key, ID):
    p = Player.simple_load(entityID, ["rankingreceiveds"])
    if p:
        if key in p.rankingreceiveds:
            return
    if not int(
            Player.pool.execute("HSET", "ranking_receiveds_p{%d}" % entityID,
                                key, "") or 0):
        return
    send_mail(entityID, title, content, addition=rewards, configID=ID)
Example #21
0
def apply_friend_offline(entityID, applyID):
    now = int(time.time())
    field = "friend_applys"
    if not Player.simple_load(entityID, []):
        return msgTips.FAIL_MSG_PLAYER_NOT_FOUND
    encode = Player.fields[field].encoder
    key = "_".join([field, "p{%d}" % entityID])
    if not Player.pool.execute(
            "HSET", key, applyID, encode({"applytime": now})):
        return msgTips.FAIL_MSG_FRIEND_ALREADY_APPLYED
    return OK
Example #22
0
def join_faction(entityID, factionID):
    faction = Faction.simple_load(factionID, [
        "level", "name", "memberset", "inviteset", "applyset",
        "strengthen_hp_level", "strengthen_at_level", "strengthen_ct_level",
        "strengthen_df_level"
    ])
    # recommend
    level = FactionRankRanking.get_score(factionID) or 1
    limit = get_config(FactionLimitConfig)[level].limit
    if limit - len(faction.memberset) <= 1:
        unrecommend(factionID)
    clean_faction(entityID)
    p = g_entityManager.get_player(entityID)
    if not p:
        p = Player.simple_load(entityID, [
            'inviteFactionSet',
            'factionID',
            'last_factionID',
            'strengthen_at_level',
            'strengthen_hp_level',
            'strengthen_ct_level',
            'strengthen_df_level',
        ])
    p.factionID = faction.factionID
    p.faction_name = faction.name
    p.faction_level = level
    now = int(time.time())
    p.joinFactionTime = now
    # FIXME
    for fid in p.inviteFactionSet:
        f = Faction.simple_load(fid, ['inviteset'])
        safe_remove(f.inviteset, p.entityID)
        f.save()
    p.inviteFactionSet.clear()
    if p.factionID != p.last_factionID:
        p.totalfp = 0
        p.todayfp_donate = 0
        p.todayfp_task = 0
        p.todayfp_sp = 0
    faction.memberset.add(p.entityID)
    safe_remove(faction.applyset, p.entityID)
    safe_remove(faction.inviteset, p.entityID)
    if g_entityManager.get_player(entityID):
        p.load_faction()
        p.sync()
    p.save()
    faction.save()
    gm_logger.info({
        'faction': {
            'entityID': p.entityID,
            'type': 'join_faction',
            'factionID': faction.factionID,
        }
    })
Example #23
0
 def build_faction_item(self, factionID, item):
     f = Faction.simple_load(
         factionID, ["name", "leaderID", "memberset"]
     )
     if f:
         l = Player.simple_load(f.leaderID, ["prototypeID"])
         item.name = f.name
         item.prototypeID = l.prototypeID
         item.faction_count = len(f.memberset)
         item.faction_level = FactionRankRanking.get_score(factionID) or 1
         item.entityID = factionID
Example #24
0
def broadcast_faction_message(m):
    msg = success_msg(msgid.RECV_MESSAGE, m)
    from entity.manager import g_entityManager
    p = g_entityManager.get_player(m.entityID)
    if not p:
        p = Player.simple_load(m.entityID, ["factionID"])
    from player.manager import g_playerManager
    from faction.model import Faction
    if p.factionID:
        g_chatManager.cache_message(m, factionID=p.factionID)
        f = Faction.simple_load(p.factionID, ["memberset"])
        if f:
            g_playerManager.broadcast(f.memberset, msg)
Example #25
0
def get_faction_thumb(factionID):
    faction = Faction.get(factionID)
    if not faction:
        return {}
    player = Player.simple_load(faction.leaderID, ['prototypeID'])
    return {
        'factionID': faction.factionID,
        'name': faction.name,
        'totalfp': faction.totalfp,
        'todayfp': faction.todayfp,
        'prototypeID': player.prototypeID,
        'mcount': len(faction.memberset),
    }
Example #26
0
def deny_apply_failure(factionID, entityID):
    faction = Faction.simple_load(factionID, ['applyset', 'leaderID'])
    safe_remove(faction.applyset, entityID)
    faction.save()
    proxy.sync_apply(faction.leaderID)
    player = Player.simple_load(entityID, ['applyFactions'])
    if is_apply(player, factionID):  # 玩家还没有取消申请
        safe_remove(player.applyFactions, factionID)
        # player.applyFactionTime = 0
        faction.save()
        player.save()
        return SUCCESS
    return msgTips.FAIL_MSG_FACTION_ALREADY_CANCEL_APPLY
Example #27
0
def send_friend_message_failure(friendID, content, senderID, **extra):
    now = time.time()
    message = {
        "time": now,
        "content": content,
    }
    message.update(extra)
    p = Player.simple_load(friendID, ['friend_messages'])
    p.friend_messages.load()
    messages = p.friend_messages.get(senderID, [])
    messages.append(message)
    p.friend_messages[senderID] = messages
    p.save()
    return True
Example #28
0
def get_gve_entity(entityID):
    p = g_entityManager.get_player(entityID)
    if not p:
        p = Player.simple_load(
            entityID,
            ["gve_index", "gve_target", "gve_state", "name", "prototypeID"])
    return {
        "id": entityID,
        "index": p.gve_index,
        "target": p.gve_target,
        "state": p.gve_state,
        "name": p.name,
        "prototypeID": p.prototypeID,
    }
Example #29
0
def send_flower_boss_mail_offline(entityID, configID, rank, damage):
    if not configID:
        return
    p = Player.simple_load(entityID, ['friendfb_kill_count'])
    p.friendfb_kill_count += 1
    config = get_config(FriendfbRewardConfig).get(configID)
    rewards = {}
    if config:
        rewards = parse_reward(config.rewards)
    p.save()
    title, content, ID = get_mail("FlowerBoss")
    content = content.format(damage, rank)
    do_send_mail(entityID, title, content, addition=rewards, configID=ID)
    return True
Example #30
0
def get_group_across_region(regionID, groupID):
    assert regionID == settings.REGION["ID"]
    g = Group.simple_load(groupID, ["name", "leaderID", "members"])
    g.members.load()
    members = []
    for k in g.members:
        p = Player.simple_load(k, ["prototypeID"])
        members.append({"entityID": p.entityID, "prototypeID": p.prototypeID})
    return {
        "name": g.name,
        "groupID": groupID,
        "regionID": regionID,
        "members": members,
    }