Example #1
0
    def get_current_user(self, env):
        """ 获取当前用户对象

        首先验证用户,当用户不能通过验证时,
        尝试登陆操作

        Args:
            env: 运行环境

        Returns:
            用户对象
        """
        # user_app = env.import_app('user')
        #
        # user = user_app.auth(env, self)
        #
        # if not user:
        #     user = user_app.login(env, self)
        # if not game_config.is_config_out():
        #     game_config.load_all()
        from logics.user import User
        uid = env.req.get_argument('user_token')
        method = env.req.get_argument('method', '')
        user = User(uid)

        return user
Example #2
0
 def approval_payment(self, admin, key, refuse=False):
     """ 审批支付
     :param key:
     :param refuse: 拒绝,默认为同意
     :return:
     """
     from admin import virtual_pay_by_admin
     from logics.user import User
     pay = self.get_payment(key)
     if pay:
         flag = False
         if not refuse:
             # 同意
             pay['status'] = 1
             u = User.get(pay['uid'])
             for i in xrange(int(pay['times'])):
                 flag = virtual_pay_by_admin(u, pay['goods_id'], pay['admin'], pay['reason'], pay['tp'])
         else:
             # 拒绝
             pay['status'] = 2
         pay['approval'] = admin         # 审批者
         self.add_approval_payment(pay)
         self.remove_payment(key)
         return flag
     return False
Example #3
0
def info(env):
    '''
    获取玩家信息
    :param env:
    :return:
    '''
    uid = env.get_argument('uid')
    uid = uid.encode('utf-8')
    if ArenaM.is_robot(uid):
        user = ArenaM.robot_generate(uid, env.user.user_m._server_name)
    elif UserM.get_server_name(uid) not in settings.SERVERS:
        return 1, {}
    else:
        user = User(uid)
    if user.regist_time:
        return 0, user.get_user_info()
    else:
        return 1, {}
Example #4
0
def get_user_server_list(req):
    """# login: 交给前端用户的server_list(此步不需要验证)
    args:
        req:    ---    arg
    returns:
        0    ---
    """
    account = req.get_argument('account', '')
    version = req.get_argument('version', '')
    # 给前端填坑
    account = account.replace('37wanA545_', '37wan_')  # 用37wan_去替换37wanA545_
    account = account.replace('pipa_new_', 'pipa_')
    replace_lua_url = True if settings.ENV_NAME in [settings.ENV_IOS, settings.ENV_STG_IOS, settings.ENV_TEST_IOS] \
                                and version >= '1.2.7' else False
    if not UnameUid.check_exist(account):
        return 0, None, {   # 查无此人
            'server_list': ServerConfig.get().server_list(replace_lua_url=replace_lua_url),     # lua的url不一样
            'current_server': '',
        }
    uu = UnameUid.get(account)
    sid, expired = uu.get_or_create_session_and_expired()
    server_list = ServerConfig.get().server_list(replace_lua_url=replace_lua_url)
    device_mark = req.get_argument('device_mark', '')
    device_mem = req.get_argument('device_mem', '')
    ip = req.request.headers.get('X-Real-Ip', '')
    for s in server_list:
        uid = s['uid'] = uu.servers.get(s['server'], '')
        s['level'] = 0
        if uid:
            u = User.get(uid)
            s['level'] = u.level
            if u.regist_time and u.name:
                commit = False
                if not (u.device_mark and u.device_mark == device_mark):
                    u.device_mark = device_mark
                    commit = True
                if not (u.device_mem and u.device_mem == device_mem):
                    u.device_mem = device_mem
                    commit = True
                if not (u.ip and u.ip == ip):
                    u.ip = ip
                    commit = True
                if u.update_session_and_expired(sid, expired):
                    commit = True
                if commit:
                    u.save()

    return 0, None, {
        'server_list': server_list,
        'current_server': '',
        'ks': sid,
    }
Example #5
0
def get_user(uid):
    """# get_user: docstring
    args:
        uid:    ---    arg
    returns:
        0    ---
    """
    import game_config
    if not game_config.is_config_out():
        game_config.load_all()

    from logics.user import User
    user = User(uid)

    setattr(user, 'game_config_version', game_config.config_version)

    return user
Example #6
0
def pay(env, *args, **kwargs):
    '''
    接受充值请求,成功则返回ok,后台进行相关修改
    :param env:
    :param args:
    :param kwargs:
    :return:
    '''
    result = {  # 应答信息模板
        'result_code': 'failed',  # 查询应答码,ok为成功,
        'result_msg': '',
        'record': {
            'timestamp': time.time(),
            'game_amount': 0,
        }
    }

    qid = env.get_argument('qid', '')
    app_key = env.get_argument('app_key', '')
    server_id = env.get_argument('server_id', '')
    order_id = env.get_argument('order_id', '')
    amount = env.get_argument('amount', '')  # 传入的amount以分为单位
    sign = env.get_argument('sign', '')

    # 验证签名
    sign_str = '%s#%s#%s#%s#%s#%s' % (amount, app_key, order_id, qid,
                                      server_id, APP_SECRET)
    if sign != hashlib.md5(sign_str).hexdigest():
        result['result_msg'] = 'sign err'
        return result

    # 获取用户uuid
    account = '%s_%s' % ('360', qid)
    if not UnameUid.check_exist(account):
        result['result_msg'] = 'user not exist!'
        return result
    um = UnameUid.get(account)
    servers = um.servers

    if server_id not in servers:
        result['result_msg'] = 'server_id not exist!'
        return result

    u = UserL.get(servers[server_id])

    pass
Example #7
0
def login(req):
    """# login: 登录用户
    args:
        req:    ---    arg
    returns:
        0    ---
        1: unicode('查无此人', 'utf-8'),
        2: unicode('接头暗号不对', 'utf-8'),
    """
    account = req.get_argument('account', '')
    platform = req.get_argument('pt', '')
    if not UnameUid.check_exist(account):
        return 1, None, {}  # 查无此人
    device_mark = req.get_argument('device_mark', '')
    device_mem = req.get_argument('device_mem', '')
    uu = UnameUid.get(account)
    sid, expired = uu.get_or_create_session_and_expired(force=True)
    server_list = ServerConfig.get().server_list()
    for s in server_list:
        uid = s['uid'] = uu.servers.get(s['server'], '')
        if uid:
            u = User.get(uid)
            commit = False
            if not (u.device_mark and u.device_mark == device_mark):
                u.device_mark = device_mark
                commit = True
            if not (u.device_mem and u.device_mem == device_mem):
                u.device_mem = device_mem
                commit = True
            if u.update_session_and_expired(sid, expired):
                commit = True

            if commit:
                u.save()

    uu.cur_platform = platform

    uu.save()

    return 0, None, {
        'server_list': server_list,
        'current_server': uu.current_server,
        'ks': sid,
    }
Example #8
0
def mark_user_login(req):
    """# mark_user_login: 标记用户最近登录,防多设备登录
    args:
        req:    ---    arg
    returns:
        0    ---
    """
    user_token = req.get_argument('user_token', '')
    device_mem = req.get_argument('device_mem', '')
    frontwindow = settings.DEBUG or req.get_argument('frontwindow', '') == '5e3b4530b293b5c1f4eeca4638ab4dc1'
    u = User.get(user_token)

    if not frontwindow and (u.device_mem and u.device_mem != device_mem):
        return 9999, None, {}

    u._mark += 1
    if settings.DEBUG:
        u.device_mark = req.get_argument('device_mark', '')
    u.save()
    return 0, None, {
        'mk': u._mark,
    }
Example #9
0
def generate_temple_robot(robot_uid, server_name, formation_index, rank=0):
    """# robot: 产生一个很拟人的机器人
    """
    import game_config
    robot_int_id = int(robot_uid.split('_')[1])
    robot_config = game_config.temple_robot.get(robot_int_id)
    ######################################################
    # ## card
    from models.cards import Cards
    card_obj = EmptyModelObj(Cards, robot_uid, server_name)

    robot_name = robot_config['name']
    if not rank:
        rank = robot_int_id + robot_config['temple_reward']

    formation_type = robot_config['formation_type'][rank % len(
        robot_config['formation_type'])]

    formation_config = game_config.temple_formation.get(formation_type)

    card_obj.formation = {
        'own': [formation_config['formation_id']],
        'current': formation_config['formation_id'],
    }

    tmp = {
        'skill_level': 1,
        'character_level': 1,
        'evo_level': 0,
        'role_level': 1,
    }

    for k in tmp:
        v = robot_config[k]
        v = range(v[1], v[0] - 1, -1)
        v = v[rank % len(v)]
        tmp[k] = v

    for _ in range(1, tmp['role_level']):
        card_obj.add_position_num(_)

    # 根据玩家等级限制上阵卡牌数量
    position_num = {
        'position_num': card_obj.position_num,
        'alternate_num': card_obj.alternate_num
    }

    formation_offset = (formation_index - 1) * 8

    for i in range(1, 9):
        if i <= 5:
            _tp = 'position_num'
            pos = i
        else:
            _tp = 'alternate_num'
            pos = i + 5

        if position_num[_tp] <= 0:
            continue
        c_id = formation_config['position%s' % (i + formation_offset)]
        if not c_id:
            continue
        card_id = card_obj.new(
            c_id,
            lv=tmp['character_level'],
            evo=tmp['evo_level'],
        )
        for _ in '12345':
            if 's_%s' % _ in card_obj._cards[card_id]:
                card_obj._cards[card_id]['s_%s' % _]['lv'] = tmp['skill_level']

        card_obj.set_alignment(card_id, pos)
        position_num[_tp] -= 1

    # ## card
    ######################################################

    ######################################################
    # ## leader_skill
    from models.skill import Skill
    leader_skill_obj = EmptyModelObj(Skill, robot_uid, server_name)
    for i in '123':
        s = robot_config['leader_skill_%s_key' % i]
        s_level = robot_config['leader_skill_%s_level' % i]
        leader_skill_obj.skill[s] = s_level
        setattr(leader_skill_obj, 'skill_' + i, s)
    # ## leader_skill
    ######################################################

    ######################################################
    # ## equip
    from models.equip import Equip
    equip_obj = EmptyModelObj(Equip, robot_uid, server_name)
    # ## equip
    ######################################################

    ######################################################
    # ## drama
    from models.drama import Drama
    drama_obj = EmptyModelObj(Drama, robot_uid, server_name)
    # ## drama
    ######################################################
    #######################################################
    # ## user
    # uid
    # user_name
    # role
    # level
    # exp

    ######################################################
    # ## arena
    from models.arena import Arena
    arena_obj = EmptyModelObj(Arena, robot_uid, server_name)
    # ## arena
    ######################################################

    from models.user import User as UserM

    user_m = EmptyModelObj(UserM, robot_uid, server_name)
    user_m.name = robot_name
    user_m.role = robot_config['role']
    user_m.level = tmp['role_level']
    user_m.regist_time = time.time() - 3600 * 24 * 10  # 注册时间戳
    user_m.active_time = time.time() - 3600 * 2
    user_m.continue_login_days = 5

    from logics.user import User
    user = User(robot_uid, user_m_obj=user_m)
    user.get = empty_func
    user.exp = user_m.exp
    for i in User._model_property_candidate_list:
        setattr(user, i[0], None)
    user.cards = card_obj
    setattr(card_obj, 'weak_user', weakref.proxy(user))
    user.equip = equip_obj
    setattr(equip_obj, 'weak_user', weakref.proxy(user))
    user.drama = drama_obj
    setattr(drama_obj, 'weak_user', weakref.proxy(user))
    user.leader_skill = leader_skill_obj
    setattr(leader_skill_obj, 'weak_user', weakref.proxy(user))
    user.arena = arena_obj
    setattr(arena_obj, 'weak_user', weakref.proxy(user))
    # ## user
    #######################################################

    return user
Example #10
0
def pyramid_robot(robot_uid,
                  robot_name,
                  server_name,
                  rank=0,
                  spec_level=0,
                  index=3,
                  evo_level=0):
    """# robot: 产生一个很拟人的机器人  金字塔机器人
    args:
        arg:    ---    arg
        rank:    机器人排名,根据此排名随机相关属性
        spec_level:    指定卡牌、用户、技能 等的级别
        第三个参数  robot_config_name='robot'
    returns:
        0    ---
    formation_type_config = {
        'formation_id': 1,
        'position1': 3800,
        'position2': 5300,
        'position3': 3000,
        'position4': 4100,
        'position5': 4000,
        'position6': 1400,
        'position7': 4700,
        'position8': 1000,
    },
    robot_config = {
        'formation_type': [1,2,3,4,5,6,7,8,9,10],
        'role': 1,
        'role_level': [41,50],
        'character_level': [67,85],
        'evo_level': [10,14],
        'skill_level': [22,23],
        'leader_skill_1_key': 201,
        'leader_skill_1_level': 5,
        'leader_skill_2_key': 212,
        'leader_skill_2_level': 5,
        'leader_skill_3_key': 232,
        'leader_skill_3_level': 4,
    }
    """
    uid = robot_uid.split('_')[index]
    uid = int(uid)
    import game_config
    robot_config = game_config.pyramid_robot.get('robot_%s' % uid)
    ######################################################
    # ## card
    from models.cards import Cards
    card_obj = EmptyModelObj(Cards, robot_uid, server_name)
    if not robot_name:
        formation_type = robot_config['formation_type'][rank % len(
            robot_config['formation_type'])]
    else:
        formation_type = random.choice(robot_config['formation_type'])
    formation_config = game_config.formation_type.get(formation_type)
    card_obj.formation = {
        'own': [formation_config['formation_id']],
        'current': formation_config['formation_id'],
    }

    tmp = {
        'skill_level': 1,
        'character_level': 1,
        'evo_level': 0,
        'role_level': 1,
    }

    if spec_level:  # 指定卡牌、用户等级
        tmp['character_level'] = spec_level
        tmp['role_level'] = spec_level
        tmp['evo_level'] = evo_level
    else:
        for k in tmp:
            v = robot_config[k]
            v = range(v[1], v[0] - 1, -1)
            v = v[rank % len(v)]
            tmp[k] = v

    for _ in range(1, tmp['role_level']):
        card_obj.add_position_num(_)

    # 根据玩家等级限制上阵卡牌数量
    position_num = {
        'position_num': card_obj.position_num,
        'alternate_num': card_obj.alternate_num
    }
    for i in range(1, 9):
        if i <= 5:
            _tp = 'position_num'
            pos = i
        else:
            _tp = 'alternate_num'
            pos = i + 5

        if position_num[_tp] <= 0:
            continue
        c_id = formation_config['position%s' % i]
        if not c_id:
            continue
        card_id = card_obj.new(
            c_id,
            lv=tmp['character_level'],
            evo=tmp['evo_level'],
        )
        for _ in '12345':
            if 's_%s' % _ in card_obj._cards[card_id]:
                card_obj._cards[card_id]['s_%s' % _]['lv'] = tmp['skill_level']

        card_obj.set_alignment(card_id, pos)
        position_num[_tp] -= 1
    # ## card
    ######################################################

    ######################################################
    # ## leader_skill
    from models.skill import Skill
    leader_skill_obj = EmptyModelObj(Skill, robot_uid, server_name)
    for i in '123':
        s = robot_config['leader_skill_%s_key' % i]
        s_level = robot_config['leader_skill_%s_level' % i]
        leader_skill_obj.skill[s] = s_level
        setattr(leader_skill_obj, 'skill_' + i, s)
    # ## leader_skill
    ######################################################

    ######################################################
    # ## equip
    from models.equip import Equip
    equip_obj = EmptyModelObj(Equip, robot_uid, server_name)
    # ## equip
    ######################################################

    ######################################################
    # ## drama
    from models.drama import Drama
    drama_obj = EmptyModelObj(Drama, robot_uid, server_name)
    # ## drama
    ######################################################

    #######################################################
    # ## user
    # uid
    # user_name
    # role
    # level
    # exp

    ######################################################
    # ## arena
    from models.arena import Arena
    arena_obj = EmptyModelObj(Arena, robot_uid, server_name)
    # ## arena
    ######################################################

    from models.user import User as UserM

    first_name = game_config.random_first_name[rank % len(
        game_config.random_first_name)]
    last_name = game_config.random_last_name[rank %
                                             len(game_config.random_last_name)]

    user_m = EmptyModelObj(UserM, robot_uid, server_name)
    # user_m.name = first_name + last_name
    user_m.name = robot_name or first_name + last_name
    user_m.role = robot_config['role']
    user_m.level = tmp['role_level']
    user_m.regist_time = time.time() - 3600 * 24 * 10  # 注册时间戳
    user_m.active_time = time.time() - 3600 * 2
    user_m.continue_login_days = 5

    from logics.user import User
    user = User(robot_uid, user_m_obj=user_m)
    user.get = empty_func
    user.exp = user_m.exp
    for i in User._model_property_candidate_list:
        setattr(user, i[0], None)
    user.cards = card_obj
    setattr(card_obj, 'weak_user', weakref.proxy(user))
    user.equip = equip_obj
    setattr(equip_obj, 'weak_user', weakref.proxy(user))
    user.drama = drama_obj
    setattr(drama_obj, 'weak_user', weakref.proxy(user))
    user.leader_skill = leader_skill_obj
    setattr(leader_skill_obj, 'weak_user', weakref.proxy(user))
    user.arena = arena_obj
    setattr(arena_obj, 'weak_user', weakref.proxy(user))
    # ## user
    #######################################################

    return user
Example #11
0
def request_handler(client_socket, addr):

    global messages_cache

    now = int(time.time())
    client = Client(client_socket)
    client_manager.add_client(client)

    client_manager.lose_time_out_clients(now)

    print_log('[%s]' % get_datetime_str(), 'connected from %s:%s' % addr,
              'client_socked_fd:', client.fileno)
    print_log('clients_num :', client_manager.get_client_count())

    while True:
        try:
            data = client_socket.recv(BUFFSIZE)
        except:
            client_manager.lose_client(client)
            break

        if not data:
            print_log('[%s]' % get_datetime_str(),
                      'client %s:%s disconnected' % addr,
                      'flag: %s, %s' % (data, type(data)))
            client_manager.lose_client(client)
            print_log('clients_num :', client_manager.get_client_count())
            break

        if data.strip().lower() == 'check':
            now = int(time.time())
            client_socket.sendall(str(process.get_memory_info()) + '|')
            client_socket.sendall('\nclients_num : %s;' %
                                  client_manager.get_client_count())
            client_socket.sendall(
                '\nper_client_connect_time: "[(fileno, uid, game_id, '
                'guild_id, server_name, vip, domain, team_id, live_time)]--> %s";'
                % str(
                    sorted([(x, y.uid, y.game_id, y.guild_id, y.server_name,
                             y.vip, y.domain, y.team_id, now - y.ttl)
                            for x, y in client_manager._clients.iteritems()],
                           key=lambda x: x[1],
                           reverse=True)))
            client_socket.sendall('\n')
            continue

        if data.strip().lower() == 'check_contents':
            client_socket.sendall(
                str(process.get_memory_info()) + '|' +
                str(id(content_factory)))
            client_socket.sendall('\ncontents : %s;' % repr([
                content.__dict__
                for content in content_factory._contents.itervalues()
            ]))
            client_socket.sendall('\n')
            continue

        if data.strip().lower() == 'quit':
            client_manager.lose_client(client)
            break

        # buffer超了指定大小还未找到规定格式的数据,主动断开连接
        if len(client.buffer) >= MAX_BUFFER_SIZE:
            client_manager.lose_client(client)
            break

        info = client.parse(data)

        if not info:
            continue

        tp = info['kqgFlag']
        if tp == 'first':
            try:
                u = User.get(info.get('uid'))
            except:
                client_manager.lose_client(client)
                break

            # if u.session_expired(info.get('ks')) or (u.device_mark and u.device_mark != info.get('device_mark'))\
            #         or (u.device_mem and u.device_mem != info.get('device_mem')):
            #     client_manager.lose_client(client)
            #     continue

            if u.is_ban:
                client_manager.lose_client(client)
                break

            client.init_info(info.get('uid'), info.get('association_id', ''),
                             info.get('game_id', ''), info.get('vip', 0),
                             info.get('domain', ''), info.get('team_id', ''),
                             addr[0], info.get('sid'), info.get('device_mark'),
                             info.get('device_mem'))

            client_manager.add_server_client(client)
            # if client.vip >= 8:
            #     receivers_vip = []
            #     for _fd, _client in client_manager.get_client_by_server_name(client.server_name).items():
            #         if _fd != client.fileno:
            #             receivers_vip.append(gevent.spawn(_client.socket.sendall, client.msg))
            #     gevent.joinall(receivers_vip)
            #
            #     content = content_factory.get(content_factory.MAPPINGS['world'], client.server_name)
            #     content.add(client.msg)
            if GAG_MSG_SWITCH:
                client.socket.sendall(force_str(get_default_msg()))

            if not GAG_MSG_SWITCH:
                content = content_factory.get(
                    content_factory.MAPPINGS['world'], client.server_name)
                msgs = content.show()
                if msgs:
                    client.socket.sendall(''.join(msgs))

                content_friend = content_factory.get(
                    content_factory.MAPPINGS['friend'], client.server_name,
                    client.uid)
                msgs = content_friend.get(client.uid)
                content_factory.delete(content_factory.MAPPINGS['friend'],
                                       client.server_name, client.uid)
                if msgs:
                    client.socket.sendall(''.join(msgs))

                client_manager.lose_repeat_clients(client)
            continue

        if tp == 'update':
            client.update_info(info.get('association_id'), info.get('domain'),
                               info.get('team_id'))

        if GAG_MSG_SWITCH:
            continue

        if client.uid in GAG_UIDS:
            continue

        u = User.get(client.uid)
        if not settings.SESSION_SWITCH and u.ip and u.ip != client.ip:
            continue

        if settings.SESSION_SWITCH and (
                u.session_expired(info.get('ks')) or
            (u.device_mark and u.device_mark != info.get('device_mark')) or
            (u.device_mem and u.device_mem != info.get('device_mem'))):
            continue

        if u.is_ban:
            continue

        next_flag = info.get('next')
        if next_flag and tp in ['world', 'system', 'guild'
                                ] and next_flag in [1, 2]:
            content = content_factory.get(content_factory.MAPPINGS[tp],
                                          client.server_name)
            msgs = content.show(next_flag)
            if msgs:
                client.socket.sendall(''.join(msgs))
            continue

        con_name = content_factory.MAPPINGS.get(tp)
        if con_name and tp not in content_factory.IGNORE:
            content = content_factory.get(con_name, client.server_name)
            content.add(client.msg)

        sendToUid = info.get('sendToUid', '')
        receivers = []
        for _fd, _client in client_manager.get_client_by_server_name(
                client.server_name).iteritems():
            if _fd == client.fileno:
                continue
            # 判断消息是否需要发送  用gevent.spawn 处理
            if tp in ['world', 'system']:  # 世界, 系统
                receivers.append(
                    gevent.spawn(_client.socket.sendall, _client.msg))
            elif tp == 'guild':  # 公会
                if _client.guild_id and _client.guild_id == client.guild_id:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))
            elif tp == 'friend' and _client.uid == sendToUid:  # 好友
                receivers.append(
                    gevent.spawn(_client.socket.sendall, client.msg))
                break
            elif tp == 'guild_war':  # 工会战
                if _client.guild_id and client.guild_id:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))
            elif tp in ['rob', 'escort']:  # 运镖, 打劫
                if client.domain and client.domain == _client.domain:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))
            elif tp == 'team':  # 队伍
                if client.team_id and client.team_id == _client.team_id:
                    receivers.append(
                        gevent.spawn(_client.socket.sendall, client.msg))

        # 私聊缓存
        if tp == 'friend' and sendToUid and not receivers:
            content = content_factory.get(content_factory.MAPPINGS[tp],
                                          client.server_name, sendToUid)
            content.add(client.msg)
            # content.save()

        gevent.joinall(receivers)
Example #12
0
def register(req):
    """# register: 注册新用户,并且将当前的uid绑定到用户上
    args:
        req:    ---    arg
    returns:
        0    ---
        1: unicode('没有用户名或者密码', 'utf-8'),
        3: unicode('这个账户已经有人了', 'utf-8'),
        5: unicode('已经绑定的账户', 'utf-8'),
        6: unicode('缺少uid', 'utf-8'),
        7:unicode('账号只能为6-20位的字母数字组合', 'utf-8')
    """
    account = req.get_argument('account', '')
    if not (account.isalnum() and 6 <= len(account) <= 20):
        return 7, None, {}
    print account, 'zzzzzzzzzzzzzzz00000000000'
    password = req.get_argument('passwd', '')
    old_account = req.get_argument('old_account', '')
    uid = req.get_argument('user_token', '')
    if not account or not password:
        return 1, None, {}          # 没有用户名或者密码
    # if not old_account:
    #     return 2, None, {}        # 没有老账户
    if UnameUid.check_exist(account):
        return 3, None, {}          # 这个账户已经有人了
    if 'fake_account_' not in old_account or not UnameUid.check_exist(old_account):
        if old_account != account:
            uu = UnameUid.get(account)
            uu.passwd = hashlib.md5(password).hexdigest()
            server_list = ServerConfig.get().server_list()
            sid, expired = uu.get_or_create_session_and_expired()
            current_server = server_list[0]['server']
            uu.current_server = current_server
            uu.save()
            print 'ddddddddddddddddd'
            return 0, None, {
                'server_list': server_list,
                'current_server': uu.current_server,
                'ks': sid,          # now + uid 唯一标识
            }
        return 5, None, {}          # 已经绑定的账户
    if uid:
        user = User.get(uid)
    else:
        return 6, None, {}          # 缺少uid
    # server_key = settings.SERVICE_NAME

    uu = UnameUid.get(old_account)
    uu.change_account_name(account)
    uu.passwd = hashlib.md5(password).hexdigest()
    # uu.servers[server_key] = user.uid
    # uu.current_server = server_key
    sid, expired = uu.get_or_create_session_and_expired(force=True)
    uu.save()

    for uid in uu.servers.itervalues():
        us = UidServer.get(uid)
        us.account = account
        us.save()

    device_mark = req.get_argument('device_mark', '')
    device_mem = req.get_argument('device_mem', '')
    user.device_mark = device_mark
    user.device_mem = device_mem
    user.update_session_and_expired(sid, expired)
    user.account = account
    user.save()

    server_list = ServerConfig.get().server_list()
    for s in server_list:
        s['uid'] = user.uid

    return 0, user, {
        'server_list': server_list,
        'current_server': uu.current_server,
        'ks': sid,
    }
Example #13
0
def new_user(req):
    """# new_user: 新进入一个分服
    args:
        env:    ---    arg
    returns:
        0    ---
        return 1, None, {}      # 必须指定account
        return 2, None, {}      # 在这个服务器上已经有账户了
    """
    role = int(req.get_argument('role', '1'))
    account = req.get_argument('account', '')   # 如果不是空字符串
    # 给前端填坑
    account = account.replace('37wanA545_', '37wan_')
    account = account.replace('pipa_new_', 'pipa_')
    platform = req.get_argument('pt', '')
    server_name = req.get_argument('server_name', '')
    if not server_name:
        server_list = ServerConfig.get().server_list()
        server_name = server_list[0]['server']

    if not account:
        return 1, None, {}                      # 必须指定account

    try:
        for_ip = req.request.headers.get('X-Forwarded-For', '')
        ip = for_ip.replace('127.0.0.1', '').replace(',', '').replace(' ', '')
    except:
        ip = ''

    uid = new_uid(server_name)
    user = User.get(uid)
    user.account = account
    user.ip = ip

    us = UidServer.get(uid)
    us.server = server_name
    us.account = account

    uu = UnameUid.get(account)
    if server_name in uu.servers:
        return 2, None, {}        # 在这个服务器上已经有账户了

    uu.servers[server_name] = uid
    uu.current_server = server_name
    uu.init_platform = platform
    sid, expired = uu.get_or_create_session_and_expired(force=True)     # 服务器中各个session_sid, session_expired过期时间

    user.update_session_and_expired(sid, expired)                       # 更新本服服务器的session_sid, session_expired
    user.role = role
    role_detail_config = game_config.role_detail[role]
    role_config = game_config.role

    user.cards.position_num = role_config[1]['position_num']            # 位置数量
    user.cards.alternate_num = role_config[1]['alternate_num']          # 助威数量
    # user.cards.open_position = [int(x) for x in role_config[1]['open_position']]      # 开启的位置
    # user.cards.formation['own'] = [role_config[1]['open_formation']]                  # 阵型
    # user.cards.formation['current'] = [role_config[1]['open_formation']]              # 当前阵型

    user.food_ability = role_detail_config['food_produce']      # 生食物能力
    user.metal_ability = role_detail_config['metal_produce']    # 生铁能力
    user.energy_ability = role_detail_config['energy_produce']
    user.harbor_ability = role_config[1]['harbor']              # 避难所等级
    user.school_ability = role_config[1]['school']              # 学校等级
    user.factory_ability = role_config[1]['factory']
    user.hospital_ability = role_config[1]['hospital']
    user.laboratory_ability = role_config[1]['laboratory']

    # 初始 food、metal 都为1000
    # user.food = 99999
    # user.metal = 99999
    # user.crystal = 99999          # 能晶
    # user.energy = 99999
    # user.coin = 99999
    user.food = 3000
    user.metal = 1000
    user.energy = 1000              # 精力
    user.coin = 20
    user.silver = 300               # 银币
    user.crystal = 50

    for i in xrange(1, 11):
        card = role_detail_config['position%d' % i]
        if not card: continue
        card_id = user.cards.new(card)
        user.cards.set_alignment(card_id, i if i <= 5 else i + 5)

    for i in role_detail_config['character_bag']:
        for j in xrange(i[1]):
            card_id = user.cards.new(i[0])

    for i in role_detail_config['item']:
        user.item.add_item(i[0], i[1])

    for i in role_detail_config['equip']:
        for ii in xrange(i[1]):
            user.equip.new(i[0])

    user.is_new = 0
    user.regist_time = int(time.time())
    user.update_regist_status(user.regist_time)
    # user.exp += 20450       # 给渠道升级爽一爽
    us.save()
    uu.save()
    user.save()
    user.cards.save()
    user.item.save()
    user.equip.save()
    return 0, user, {'uid': user.uid, 'ks': sid}
Example #14
0
def get_user_server_list_huawei(req):
    """# login: 交给前端用户的server_list(此步不需要验证)
    args:
        req:    ---    arg
    returns:
        0    ---
    """
    account = req.get_argument('account')
    old_account = req.get_argument('old_account')
    if not UnameUid.check_exist(account) and not UnameUid.check_exist(old_account):
        return 0, None, {       # 查无此人
            'server_list': ServerConfig.get().server_list(),
            'current_server': '',
        }
    if UnameUid.check_exist(account):
        uu = UnameUid.get(account)
    else:
        if UnameUid.check_exist(old_account):
            uu = UnameUid.get(account)
            old_uu = UnameUid.get(old_account)
            for k in uu._attrs.iterkeys():
                setattr(uu, k, getattr(old_uu, k))
                uu.save()
            old_uu_copy_key = old_account + '____copy'
            uu_copy = UnameUid.get(old_uu_copy_key)
            for k in uu_copy._attrs.iterkeys():
                setattr(uu_copy, k, getattr(old_uu, k))
                uu_copy.save()
            old_uu.redis.delete(old_uu._model_key)
            del old_uu
        else:
            return 0, None, {   # 查无此人
                'server_list': ServerConfig.get().server_list(),
                'current_server': '',
            }
    sid, expired = uu.get_or_create_session_and_expired()
    device_mark = req.get_argument('device_mark', '')
    device_mem = req.get_argument('device_mem', '')
    ip = req.request.headers.get('X-Real-Ip', '')
    server_list = ServerConfig.get().server_list()
    for s in server_list:
        uid = s['uid'] = uu.servers.get(s['server'], '')
        s['level'] = 0
        if uid:
            u = User.get(uid)
            s['level'] = u.level
            if u.regist_time and u.name:
                commit = False
                if not (u.device_mark and u.device_mark == device_mark):
                    u.device_mark = device_mark
                    commit = True
                if not (u.device_mem and u.device_mem == device_mem):
                    u.device_mem = device_mem
                    commit = True
                if not (u.ip and u.ip == ip):
                    u.ip = ip
                    commit = True
                if u.update_session_and_expired(sid, expired):
                    commit = True
                if commit:
                    u.save()

    return 0, None, {
        'server_list': server_list,
        'current_server': '',
        'ks': sid,
    }
Example #15
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from run import settings
from logics.share import debug_sync_change_time

import datetime
import time
import game_config

from logics.user import User
from lib.db import ModelBase
from models.user import User as um
from models.payment import *
c = um.get('h11234567').redis
import sys
uid = sys.argv[1] if len(sys.argv) > 1 else 'h11234567'
u = User.get(uid)

if settings.DEBUG:
    debug_sync_change_time()