Beispiel #1
0
 def giftkey(self, msgtype, body):
     from protocol.poem_pb import Giftkey, GiftkeyResponse
     from config.configs import get_config, GiftkeyConfig
     from reward.manager import open_reward, build_reward_msg, RewardType
     from giftkey import use_key, InvalidGiftkeyError, ExceedUseCountError, ExceedDeallineError
     player = self.player
     req = Giftkey()
     req.ParseFromString(body)
     try:
         giftID = use_key(player, req.key)
     except InvalidGiftkeyError:
         return fail_msg(msgtype, reason='无效的兑换码')
     except ExceedUseCountError:
         return fail_msg(msgtype, reason='已经达到最大兑换次数了')
     except ExceedDeallineError:
         return fail_msg(msgtype, reason='已经超过有效期了')
     gift = get_config(GiftkeyConfig)[giftID]
     reward = open_reward(RewardType.Giftkey, gift)
     result = reward.apply(player)
     player.save()
     player.sync()
     rsp = GiftkeyResponse()
     build_reward_msg(rsp, result)
     gm_logger.info(
         {'giftkey': {
             'entityID': player.entityID,
             'giftkey': req.key
         }})
     return success_msg(msgtype, rsp)
Beispiel #2
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()
Beispiel #3
0
def create_user(request):
    req = poem_pb.RegisterRequest()
    req.ParseFromString(request.body)
    clientIP = request.env.get('REMOTE_ADDR', '')
    username = req.username
    password = req.password
    # 大小包处理
    try:
        if UsernameIndexing.exists(username):
            raise RegisterError(_YYTEXT(u'该帐号已被注册,请重新输入'))
        user = register(username, password, get_device_id(req.deviceInfo))
    except RegisterError as e:
        raise ApplicationError(0, e.message)

    info = unpack_login_info(req.deviceInfo,
                             userID=user.userID,
                             username=user.username,
                             featureCode=req.featureCode,
                             clientIP=clientIP)

    info.update({
        'userID': user.userID,
        'username': user.username,
        'type': 'register'
    })
    gm_logger.info({'sessionaccess': info})
    account_register.info(**info)

    return poem_pb.RegisterResponse(username=user.username)
Beispiel #4
0
 def rpccall(self, key, *args, **kwargs):
     player = self.player
     if player:
         gm_logger.info({
             'behavior': {
                 'entityID': player.entityID,
                 'msgid': clean_msgtype(key),
             }
         })
     return super(BaseService, self).rpccall(key, *args, **kwargs)
Beispiel #5
0
 def faction_create(self, msgtype, body):
     p = self.player
     # 判断是否可以创建公会
     if p.factionID:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FACTION_ALREADY_HAD_FACTION)
     # if is_applied(p):
     #     return fail_msg(
     #         msgtype, msgTips.FAIL_MSG_FACTION_ALREADY_APPLYED)
     req = poem_pb.AlterNameFaction()
     req.ParseFromString(body)
     name, err = validate_name(req.name)
     if err:
         return fail_msg(msgtype, err)
     try:
         FactionnameIndexing.register(0, name)  # 占位
     except DuplicateIndexException:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FACTION_DUPLICATE_FACTION_NAME)
     try:
         now = int(time.time())
         faction = Faction.create(name=name,
                                  createtime=now,
                                  leaderID=p.entityID)
     except EntityExistsException:
         FactionnameIndexing.unregister(name)
         return fail_msg(msgtype, msgTips.FAIL_MSG_FACTION_CREATE_FAIL)
     try:
         apply_reward(p, {},
                      cost={'gold': 500},
                      type=RewardType.CreateFaction)
     except AttrNotEnoughError:
         FactionnameIndexing.unregister(name)
         return fail_msg(msgtype, msgTips.FAIL_MSG_FACTION_NOT_ENOUGH_GOLD)
     FactionnameIndexing.pool.execute('HSET', FactionnameIndexing.key, name,
                                      faction.entityID)  # 更新
     faction.save()
     gm_logger.info({
         'faction': {
             'entityID': p.entityID,
             'type': 'create_faction',
             'factionName': faction.name,
             'factionLevel': 1,
             'factionID': faction.factionID,
         }
     })
     join_faction(p.entityID, faction.factionID)
     p.faction_is_leader = True
     p.save()
     p.sync()
     recommend(faction.factionID)  # 加入推荐列表
     FactionRankRanking.update_score(faction.factionID, 1)
     rsp = poem_pb.FactionInfo(**get_faction_info(faction.factionID))
     return success_msg(msgtype, rsp)
Beispiel #6
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,
        }
    })
Beispiel #7
0
    def create_role(self, msgtype, body):
        limited, message = self.access_limited()
        if limited:
            return fail_msg(msgtype, reason=message)
        req = poem_pb.CreateRoleRequest()
        req.ParseFromString(body)
        modelID = req.iconID
        user = User.load(self.userID)
        roleID = user.roles.get(settings.REGION['ID'])
        if roleID:
            return fail_msg(msgtype, msgTips.FAIL_MSG_ALREADY_CREATEROLE)
        name, error = validate_name(req.name)
        if error:
            return fail_msg(msgtype, error)

        # 名字去重复
        try:
            PlayernameIndexing.register(0, name)  # 占位
            player = Player.create(name=name, modelID=modelID, sex=req.sex, level=1, career=req.school)
            player.save()
            PlayernameIndexing.pool.execute('HSET', PlayernameIndexing.key, name, player.entityID)  # 更新
        except DuplicateIndexException:
            return fail_msg(msgtype, reason=_YYTEXT('该名称已存在'))
        except EntityExistsException:  # 已经存在的entityID, 一般由于自增ID被清零,但entityID数据还存在
            return fail_msg(msgtype, reason=_YYTEXT('该名称已存在'))
        if not player or not player.entityID:
            PlayernameIndexing.unregister(name)
            return fail_msg(msgtype, reason=_YYTEXT('该名称已存在'))
        PlayerLevelRanking.update_score(player.entityID, player.level)
        user.roles[settings.REGION['ID']] = player.entityID
        user.save()
        rsp = poem_pb.CreateRoleResponse()
        rsp.roleId = player.entityID
        role = rsp.roles.add()
        role.name, role.level, role.resourceId, role.school, role.sex = \
            player.name, player.level, player.modelID, player.career, player.sex

        from common.log import gm_logger
        gm_logger.info({'createrole': {'entityID': player.entityID,
                                       'userID': self.userID,
                                       'type': 'createrole',
                                       'username': player.username,
                                       'playername': player.name,
                                       'worldID': settings.SESSION['ID'],
                                       'createrolename': player.name,
                                       'career': player.career,
                                       'username_alias': user.username_alias}})
        role.id = rsp.roleId
        return success_msg(msgtype, rsp)
Beispiel #8
0
 def faction_levelup(self, msgtype, body):
     '''只有会长能操作'''
     player = self.player
     factionID = player.factionID
     if not factionID:
         return fail_msg(msgtype, msgTips.FAIL_MSG_FACTION_HAS_NOT_FACTION)
     faction = Faction.simple_load(factionID, ['leaderID'])
     if player.entityID != faction.leaderID:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FACTION_PERMISSION_DENIED)
     level = FactionRankRanking.get_score(factionID) or 0
     configs = get_config(FactionLimitConfig)
     config = configs.get((level or 1) + 1)
     if not config:
         return fail_msg(msgtype, msgTips.FAIL_MSG_FACTION_MAX_LEVEL)
     faction = Faction.load(factionID)
     if faction.totalfp < config.exp:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FACTION_NOT_ENOUGH_TOTALFP)
     faction.incr('totalfp', -config.exp)
     faction.save()
     if not level:
         incr = 2
     else:
         incr = 1
     rs = FactionRankRanking.incr_score(factionID, incr)
     limit1 = get_config(FactionLimitConfig)[level or 1]
     limit2 = get_config(FactionLimitConfig).get((level or 1) + 1)
     if limit2 and limit2.limit > limit1.limit:
         recommend(factionID)
     player.save()
     player.sync()
     notify_change(factionID)
     gm_logger.info({
         'faction': {
             'entityID': player.entityID,
             'type': 'levelup_faction',
             'factionLevel': rs,
             'factionID': faction.factionID,
         }
     })
     return success_msg(msgtype, '')
Beispiel #9
0
def save_guide(player, guide_type):
    # 保存新手引导进度
    if not guide_type:
        return
    if guide_type in player.guide_types:
        return
    from common.log import gm_logger
    from scene.constants import FbType
    fbinfo = get_config(FbInfoByTypeConfig).get(FbType.Normal, [])
    maxfb = max(set(player.fbscores) & set(e.ID for e in fbinfo) or [0])
    gm_logger.info({"guide": {
        "entityID": player.entityID,
        "type": "guide_%s" % guide_type,
        "userID": player.userID,
        "username": player.username,
        "data": {"fbID": maxfb},
    }})
    player.guide_types.add(guide_type)
    player.set_dirty('guide_types')
    player.save()
Beispiel #10
0
def throne_member(factionID, entityID):
    player = g_entityManager.get_player(entityID)
    faction = Faction.simple_load(factionID, ['entityID', 'memberset'])
    if player.factionID == factionID:
        if int(time.time()) - player.joinFactionTime <= THRONEFACTIONCD:
            return msgTips.FAIL_MSG_FACTION_CAN_NOT_THRONE_TO_NEWER
        faction.leaderID = player.entityID
        faction.save()
        player.faction_is_leader = True
        player.save()
        player.sync()
        gm_logger.info({
            'faction': {
                'entityID': player.entityID,
                'type': 'throne_faction',
                'factionID': faction.factionID,
            }
        })
        return SUCCESS
    return msgTips.FAIL_MSG_FACTION_IS_NOT_IN_FACTION
Beispiel #11
0
 def faction_alter_name(self, msgtype, body):
     p = self.player
     factionID = self.player.factionID
     if not factionID:
         return fail_msg(msgtype, msgTips.FAIL_MSG_FACTION_HAS_NOT_FACTION)
     faction = Faction.simple_load(factionID, ['leaderID', 'name'])
     if self.player.entityID != faction.leaderID:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FACTION_PERMISSION_DENIED)
     req = poem_pb.AlterNameFaction()
     req.ParseFromString(body)
     cost = get_cons_value("FactionAlterNameGold")
     if p.gold < cost:
         return fail_msg(msgtype, reason="钻石不足")
     name, err = validate_name(req.name)
     if err:
         return fail_msg(msgtype, err)
     try:
         FactionnameIndexing.register(factionID, req.name)
     except DuplicateIndexException:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FACTION_DUPLICATE_FACTION_NAME)
     FactionnameIndexing.unregister(faction.name)
     apply_reward(p, {},
                  cost={"gold": cost},
                  type=RewardType.FactionAlterName)
     faction.name = req.name
     p.save()
     p.sync()
     faction.save()
     notify_change(factionID)
     gm_logger.info({
         'faction': {
             'entityID': p.entityID,
             'type': 'altername_faction',
             'factionName': faction.name,
             'factionID': faction.factionID,
         }
     })
     return success_msg(msgtype, '')
Beispiel #12
0
def cleanup(player):
    if not player:
        return
    PlayerOnlineIndexing.unregister(player.entityID)
    player.save_on_quit()
    logger.info('player quit %d', player.entityID)
    g_entityManager.unload_player(player.entityID)
    g_playerManager.close_player(player.entityID)
    logger.info('clean up %d', player.entityID)
    if player.lastlogin and player.lastlogout:
        onlinetimes = (player.lastlogout - player.lastlogin).total_seconds()
    else:
        onlinetimes = 0
    gm_logger.info({
        'access': {
            'entityID': player.entityID,
            'type': 'logout',
            'userID': player.userID,
            'username': player.username,
            'onlinetimes': onlinetimes,
            'username_alias': player.username_alias,
            'channel': player.channel
        }
    })
Beispiel #13
0
 def itunes_iap_validation_handle(self, msgtype, req):
     from itunesiap import Request, set_verification_mode
     from itunesiap.exceptions import InvalidReceipt, ItunesServerNotAvailable
     from session.utils import sdk_username
     from sdk.payment import end_payment, get_payment, gen_payment
     player = self.player
     try:
         # set_verification_mode('sandbox')
         request = Request(req.receipt)
         with request.verification_mode('review'):
             receipt = request.verify()
         logger.info(receipt)
         configs = get_config(RechargeConfig)
         goods = filter(
             lambda item: item.goodsid == receipt.product_id and item.
             sdktype == poem_pb.SDK_APP_IOS, configs.values())
         if len(goods) != 1:
             logger.error('Invalid goodsid: {},{}'.format(
                 player.entityID, receipt.product_id))
             return False
         goods = goods[0]
         logger.debug(goods)
         sdkorderid = sdk_username(poem_pb.SDK_APP_IOS,
                                   receipt.transaction_id)
         payment = get_payment(sdkorderid)
         if not payment:
             result = gen_payment(sdkorderid, player.entityID,
                                  poem_pb.SDK_APP_IOS, receipt.product_id)
             payment = get_payment(sdkorderid)
         if payment.get('status', None) != 'SUCCESS':
             if not end_payment(sdkorderid):
                 logger.error('insert callback pay record failed %s' %
                              sdkorderid)
                 return False
             payment = get_payment(sdkorderid)
             logger.debug(payment)
             data = {
                 "clientVersion": "",
                 "amount": goods.amount,
                 "orderNO": sdkorderid,
                 "_level": "",
                 "_username": "",
                 "_userID": 0,
                 "_entityID": player.entityID,
                 "result": 1
             }
             username = player.username
             userID = player.userID
             idfa = player.idfa
             appid = player.appid
             rs = pay_handler(player.entityID,
                              username,
                              payment["goodsid"],
                              amount=int(goods.amount))
             if not rs:
                 return False
             logger.debug(rs)
             get_gold = rs["get_gold"]
             username = rs["username"]
             level = rs["level"]
             rsp = poem_pb.PayResult(success=True,
                                     roleID=player.entityID,
                                     userID=0,
                                     payID=receipt.transaction_id,
                                     goods=0,
                                     count=get_gold,
                                     data=req.receipt)
             g_playerManager.sendto(player.entityID,
                                    success_msg(msgid.SDK_PAY_RESULT, rsp))
             data.update(_username=username, _level=level)
             data.update(_gold=get_gold)
             role_credit(**data)
             gm_logger.info({
                 'pay': {
                     'transaction_id': receipt.transaction_id,
                     'userID': userID,
                     'entityID': player.entityID,
                     'channel': player.channel,
                     'amount': goods.amount,
                     'gold': get_gold,
                     'idfa': idfa,
                     'appid': appid,
                     'username': username
                 },
                 'payID': sdkorderid
             })
         if payment.get('status', None) == 'SUCCESS':
             response = poem_pb.iTunesStoreReceiptResponse()
             response.transaction_id = receipt.transaction_id
             response.successed = True
             g_playerManager.sendto(player.entityID,
                                    success_msg(msgtype, response))
     except InvalidReceipt:
         logger.warning('invalid receipt')
Beispiel #14
0
    def enter(self, msgtype, body):
        req = poem_pb.EnterRequest()
        req.ParseFromString(body)
        entityID = req.entityID
        # 不允许重新登录
        if g_playerManager.has_player(entityID):
            if g_playerManager.peers[entityID].key == self.peer.key:
                return
            # 给已登录的发送重复登录消息
            g_playerManager.sendto(entityID,
                                   fail_msg(msgtype, msgTips.FAIL_MSG_KICKED))
            g_playerManager.kick_player(entityID)
        clientVersion = req.clientVersion
        featureCode = req.featureCode
        clientIP, _ = self.peer._sock.getpeername() or ('', '')
        self.player = player = g_entityManager.load_player(
            self.userID, entityID, clientVersion, featureCode, clientIP)
        if not player:
            self.peer.sender(fail_msg(msgtype, msgTips.FAIL_MSG_LOAD_PLAYER))
            self.peer.close()
            return
        PlayerOnlineIndexing.update(settings.WORLD["ID"], player.entityID)
        player.clientVersion = clientVersion
        player.featureCode = featureCode
        player.clientIP = clientIP
        player.appid = req.deviceInfo.appid
        player.UDID = req.deviceInfo.UDID
        player.idfa = req.deviceInfo.idfa
        player.IMEI = req.deviceInfo.IMEI
        player.MAC = req.deviceInfo.MAC
        player.save()
        g_playerManager.register(player.entityID, self.peer)
        player.sync(all=True)

        # 发送公告
        notice_rsp = get_notice_rsp()
        g_playerManager.sendto(player.entityID,
                               success_msg(msgid.NOTICE, notice_rsp))

        sync_scene_infos(player)

        rsp = poem_pb.EnterResponse()
        rsp.ENABLE_GIFTKEY = settings.ENABLE_GIFTKEY  # cdkey
        rsp.REV = settings.REV
        rsp.time = int(time.time())
        self.peer.sender(success_msg(msgtype, rsp))

        gm_logger.info({
            'access': {
                'entityID': player.entityID,
                'type': 'login',
                'userID': player.userID,
                'username': player.username,
                'onlines': g_playerManager.count(),
                'username_alias': player.username_alias,
                'channel': player.channel
            }
        })

        from common.log import role_login
        role_login(player=player)
Beispiel #15
0
def _set_plan(player, task, today, value=1, replace=False):
    realID = task.ID
    configs = get_config(TaskConfig)
    info = task
    taskID = info.sameID
    task = player.tasks.get(taskID, {})
    if not info:
        return
    logger.debug('set taskID {} value {}'.format(taskID, value))
    if not replace:
        if task.get('when'):
            when = datedate.fromtimestamp(task['when'])
            plan = task.get('plan', 0)
            prev = configs.get(info.prev)
            if prev:
                init = prev.goal
            else:
                init = 0
            if info.type in (TaskType.Daily, TaskType.Faction,
                             TaskType.Trigger):
                if when != today:
                    task['plan'] = init + value
                else:
                    if not plan:
                        task['plan'] = init + value
                    else:
                        task['plan'] += value
            elif info.type == TaskType.Sign:
                if (when.year, when.month) != (today.year, today.month):
                    task['plan'] = init + value
                else:
                    if not plan:
                        task['plan'] = init + value
                    else:
                        task['plan'] += value
            else:
                if not plan:
                    task['plan'] = init + value
                else:
                    task['plan'] += value
        else:
            task['plan'] = value
    else:
        task['plan'] = value
    task['when'] = int(time.time())
    logger.debug("{} {}".format(taskID, task))
    isdone = task['plan'] >= info.goal
    if isdone:
        info = configs[realID]
        player.taskrewards.add(realID)
        if info.type == TaskType.Faction:
            player.faction_taskID = 0
            player.faction_task_done = True
        elif info.type == TaskType.Trigger:
            pass
        from common.log import gm_logger
        t = {TaskType.Normal: "主线"}
        info = configs[realID]
        gm_logger.info({
            'task': {
                'entityID': player.entityID,
                'userID': player.userID,
                'username': player.username,
                'data': {
                    'taskID': realID
                },
                'type': t.get(info.type, "支线"),
            }
        })
    player.tasks[taskID] = task
    return isdone
Beispiel #16
0
def sdk_pay(entityID,
            orderid,
            amount,
            rechargegold,
            sdata,
            sdktype,
            goods,
            delay=0):
    from session.utils import sdk_username
    from sdk.payment import end_payment, get_payment
    GOOD_GOLD = 0

    if orderid:
        sdkorderid = sdk_username(sdktype, orderid)
        payment = get_payment(sdkorderid)
        if len(payment) == 0:
            logger.error('orderid {} not exists.'.format(orderid))
            return False
        # 如果交易完成直接返回成功
        if payment.get('status', None) == 'SUCCESS':
            return True

        if not end_payment(sdkorderid):
            logger.error('insert callback pay record failed %s' % sdkorderid)
            return False
        goodsid = payment["goodsid"]

    elif sdktype == poem_pb.SDK_YYB:
        sdkorderid = sdk_username(sdktype, '')
        ids = get_config(RechargeBySdktypeConfig).get(sdktype, [])
        configs = [get_config(RechargeConfig)[e.id] for e in ids]
        goodsid = max(configs, key=lambda o: o.amount).goodsid

    else:
        logger.error('orderid {} is empty.'.format(orderid))
        return False

    amount = amount / 10.0
    gold = rechargegold
    if goods == GOOD_GOLD:
        data = {
            "clientVersion": "",
            "amount": gold,
            "orderNO": sdkorderid,
            "_level": "",
            "_username": "",
            "_userID": 0,
            "_entityID": entityID,
            "result": 1
        }
        player = g_entityManager.get_player(entityID)
        if player:
            username = player.username
            userID = player.userID
            playername = player.name
            channel = player.channel
        else:
            p = Player.simple_load(entityID,
                                   ["username", "userID", "name", "channel"])
            username = p.username
            userID = p.userID
            playername = p.name
            channel = p.channel
        rs = pay_handler(entityID, username, goodsid, amount=amount)
        if not rs:
            return False
        get_gold = rs["get_gold"]
        username = rs["username"]
        level = rs["level"]
        if player:
            rsp = poem_pb.PayResult(success=True,
                                    roleID=entityID,
                                    userID=userID,
                                    payID=orderid,
                                    goods=0,
                                    count=get_gold,
                                    data=sdata)
            if delay == 0:
                g_playerManager.sendto(player.entityID,
                                       success_msg(msgid.SDK_PAY_RESULT, rsp))
            else:

                def do_send():
                    gevent.sleep(delay)
                    g_playerManager.sendto(
                        player.entityID, success_msg(msgid.SDK_PAY_RESULT,
                                                     rsp))

                gevent.spawn(do_send)
        data.update(_username=username, _level=level)
        data.update(_gold=get_gold)
        role_credit(**data)
        gm_logger.info({
            'pay': {
                'entityID': entityID,
                'amount': amount,
                'userID': userID,
                'playername': playername,
                'channel': channel,
                'gold': get_gold,
                'username': username,
                'transaction_id': orderid
            },
            'payID': sdkorderid
        })
        return True
    logger.error('unknown goods %d', goods)
    return False
Beispiel #17
0
def apply_reward(role,
                 reward,
                 cost=None,
                 type=RewardType.Undefined,
                 force=True,
                 extra=None):
    # reward like {'gold':10, 'exp':10, 'petList':[[30000001, 1]]}
    # force 不检查限制
    reward = dict(reward or {})
    reward_ = dict(reward or {})
    petList = reward.pop('petList', [])
    matList = reward.pop('matList', [])
    patList = reward.pop('petPatchList', [])  # FIXME
    equipList = reward.pop('equipList', [])
    gemList = reward.pop('gemList', [])
    specPacks = reward.pop('specPacks', [])
    p_in_specPacks = 0
    e_in_specPacks = 0
    from config.configs import get_config
    packs = get_config(SpecpackConfig)
    for packID, count in specPacks:
        pack = packs[packID]
        if pack.ref_type == RewardItemType.Equip:
            e_in_specPacks += count
        elif pack.ref_type == RewardItemType.Pet:
            p_in_specPacks += count
    if not force:
        if petList:
            if not check_add_pets(role, len(petList) + p_in_specPacks):
                raise PetExceedError
        if matList:
            if not check_add_mats(role, len(matList)):
                raise MatExceedError
        if equipList:
            if not check_add_equips(role, len(equipList) + e_in_specPacks):
                raise EquipExceedError
        if gemList:
            if not check_add_gems(role, len(gemList)):
                raise GemExceedError
    if cost:
        _cost(role, cost, type)
    if reward_:
        add_pets(role, petList, extra=extra)
        add_mats(role, matList)
        add_pats(role, patList)  # FIXME 已经不再使用
        add_attr(role, reward)
        add_equips(role, equipList, extra=extra)
        add_specpacks(role, specPacks)
        add_gems(role, gemList)
        # {{{
        from common.log import gm_logger
        if isinstance(role, Player):
            player = role
        else:
            from entity.manager import g_entityManager
            player = g_entityManager.get_player(role.masterID)
        gm_logger.info({
            'gain': {
                'entityID': player.entityID,
                'data': reward_,
                'type': type
            }
        })
        from common.log import role_debit
        for prototypeID, amount in petList:
            role_debit(player=player,
                       debitType=role_debit.Gain,
                       itemType=type,
                       argID=prototypeID,
                       argAmount=amount)
        for prototypeID, amount in equipList:
            role_debit(player=player,
                       debitType=role_debit.Gain,
                       itemType=type,
                       argID=prototypeID,
                       argAmount=amount)
        for matID, amount in matList:
            role_debit(player=player,
                       debitType=role_debit.Gain,
                       itemType=type,
                       argID=matID,
                       argAmount=amount)
        for gemID, amount in gemList:
            role_debit(player=player,
                       debitType=role_debit.Gain,
                       itemType=type,
                       argID=gemID,
                       argAmount=amount)
        for attr, amount in reward.items():
            if not check_attr(attr) or amount == 0:
                continue
            role_debit(
                player=player,
                debitType=role_debit.Gain,
                itemType=type,
                currency=RewardItemTypeDict[attr],
                amount=amount,
                balance=getattr(player, attr, 0),
            )
        # }}}
    role.save()
    return reward_
Beispiel #18
0
def cost(role, cost, type):
    cost_ = dict(cost)
    matList = cost.pop('matList', [])
    petList = cost.pop('petList', [])
    patList = cost.pop('petPatchList', [])
    equipList = cost.pop('equipList', [])
    gemList = cost.pop('gemList', [])

    # CHECK
    check_cost_mats(role, matList)
    check_cost_pets(role, petList)
    check_cost_equips(role, equipList)
    check_cost_gems(role, gemList)
    check_cost_attr(role, cost)

    cost_mats(role, matList)
    cost_pets(role, petList)
    cost_equips(role, equipList)
    cost_gems(role, gemList)

    if not cost_pats(role, patList):
        raise PatNotEnoughError

    # {{{cost log
    from common.log import gm_logger
    if isinstance(role, Player):
        player = role
    else:
        from entity.manager import g_entityManager
        player = g_entityManager.get_player(role.masterID)

    gm_logger.info(
        {'cost': {
            'entityID': player.entityID,
            'data': cost_,
            'type': type
        }})
    # }}}
    cost_attr(role, cost)
    # {{{
    from common.log import role_debit
    for prototypeID, amount in petList:
        role_debit(player=player,
                   debitType=role_debit.Cost,
                   itemType=type,
                   argID=prototypeID,
                   argAmount=amount)
    for matID, amount in matList:
        role_debit(player=player,
                   debitType=role_debit.Cost,
                   itemType=type,
                   argID=matID,
                   argAmount=amount)
    for patchid, amount in patList:
        role_debit(player=player,
                   debitType=role_debit.Cost,
                   itemType=type,
                   argID=-patchid,
                   argAmount=amount)
    for prototypeID, amount in equipList:
        role_debit(player=player,
                   debitType=role_debit.Cost,
                   itemType=type,
                   argID=prototypeID,
                   argAmount=amount)
    for prototypeID, amount in gemList:
        role_debit(player=player,
                   debitType=role_debit.Cost,
                   itemType=type,
                   argID=prototypeID,
                   argAmount=amount)
    for attr, amount in cost.items():
        if not check_attr(attr) or amount == 0:
            continue
        role_debit(
            player=player,
            debitType=role_debit.Cost,
            itemType=type,
            currency=RewardItemTypeDict[attr],
            amount=amount,
            balance=getattr(player, attr, 0),
        )
    # }}}
    return cost_
Beispiel #19
0
def common_login(request,
                 raw_username,
                 req,
                 auto_register=False,
                 check_password=True):
    # 检查版本
    try:
        clientversion = int(getattr(req.deviceInfo, 'clientVersion', 1))
    except ValueError:
        clientversion = 1

    if get_device_id(req.deviceInfo) in g_block_devices:
        raise ApplicationError(0, u"该设备已被禁止登录 如有疑问请联系客服")
    if get_g_version() and clientversion and get_g_version() > clientversion:
        raise ApplicationError(msgTips.FAIL_MSG_LOGIN_OLDVERSION,
                               settings.CLIENTOLDVERSION_NOTICE)

    username = raw_username

    # 检查白名单
    if username not in g_whitelist:
        raise ApplicationError(0, get_loginlimitmsg())

    # 查找用户
    userID = UsernameIndexing.get_pk(username)
    if userID:
        user = User.get(userID)
        user.load_containers()

        # 检查设备锁定
        if user.lock_device and get_device_id(
                req.deviceInfo) != user.lock_device:
            raise ApplicationError(0, u'该帐号为试玩帐号,只能在注册时的使用的设备上登录!')
    else:
        user = None

    clientIP = request.env.get('REMOTE_ADDR', '')
    password = getattr(req, 'password', '') or "dummy"

    if not user and auto_register:
        # register
        try:
            user = register(raw_username, password,
                            get_device_id(req.deviceInfo))
        except RegisterError as e:
            raise ApplicationError(0, e.message)

        # 创建成功
        userID = user.userID
        info = unpack_login_info(req.deviceInfo,
                                 userID=userID,
                                 username=user.username,
                                 featureCode=req.featureCode,
                                 clientIP=clientIP)
        info.update({
            'userID': userID,
            'username': user.username,
            'type': 'register'
        })
        gm_logger.info({'sessionaccess': info})
        account_register.info(**info)

    if not user:
        raise ApplicationError(msgTips.FAIL_MSG_LOGIN_WRONG_ACCOUNT)

    # 检查密码
    userID = user.userID
    if check_password:
        hashed = user.password
        if not utils.check_password(password, hashed):
            raise ApplicationError(msgTips.FAIL_MSG_INVALID_PASSWORD)

    # 检查封停
    now = int(time.time())
    if user.blocktime and user.blocktime > now:
        raise ApplicationError(0, u"该账号已被禁止登录 如有疑问请联系客服")
    if user.imsi in g_block_devices:
        raise ApplicationError(0, u"该账号已被禁止登录 如有疑问请联系客服")

    do_login(request, userID)
    user.lastserver = req.regionID
    user.save()

    # log
    info = unpack_login_info(req.deviceInfo,
                             userID=userID,
                             username=user.username,
                             featureCode=req.featureCode,
                             clientIP=clientIP)
    info.update({'userID': userID, 'username': user.username, 'type': 'login'})
    gm_logger.info({'sessionaccess': info})
    account_login.info(**info)

    # 响应
    entityIDs = user.roles.get(req.regionID, [])
    return poem_pb.HTTPLoginResponse(
        userID=userID,
        sdk_username=user.username,
        world=encode_world(
            route(req.regionID, entityIDs[0] if entityIDs else None)),
        verify_code=request.sid,
    )