Exemplo n.º 1
0
def loads_table(room_id):
    raw = redis.get("table:{0}".format(room_id))
    # print "table", room_id, raw
    if not raw:
        return
    data = json.loads(raw)

    table = Table(room_id, None, None, None)
    for k, v in data.items():
        if k in ("logger", "conf", "player_dict", "seat_dict", "machine",
                 "reward_info"):
            continue
        else:
            table.__dict__[k] = v

    table.conf = TableConf(table.kwargs)
    table.request = WebRequest(room_id, table.room_uuid, table.conf.game_type,
                               table.conf.app_id, table.owner)

    for i in data["player_dict"]:
        table.player_dict[i] = loads_player(i, table)

    for i, j in data["seat_dict"].items():
        table.seat_dict[int(i)] = table.player_dict[j]
    if "reward_info" in data:
        for i, j in data["reward_info"].items():
            table.reward_info[int(i)] = j
    # 设置重连暂停状态
    table.pasue_state = True

    state = data["machine"]
    table.machine.last_state = table_state[state[0]] if state[0] else None
    table.machine.cur_state = table_state[state[1]] if state[1] else None
    return table
Exemplo n.º 2
0
def loads_table(room_id):
    raw = redis.get("table:{0}".format(room_id))
    # print "table", room_id, raw
    if not raw:
        return
    data = pickle.loads(raw)

    table = Table(room_id, None, "", 0, 0, None, None)
    for k, v in data.items():
        if k in ("logger", "conf", "player_dict", "seat_dict", "machine",
                 "lookon_player_dict"):
            continue
        else:
            table.__dict__[k] = v

    table.conf = TableConf(table.kwargs)
    table.chairs = table.conf.max_chairs

    for i in data["player_dict"]:
        player = loads_player(i, table)
        if player:
            table.player_dict[i] = player

    for i, j in data["seat_dict"].items():
        if j in table.player_dict:
            table.seat_dict[int(i)] = table.player_dict[j]

    state = data["machine"]
    table.machine.last_state = table_state[state[0]] if state[0] else None
    table.machine.cur_state = table_state[state[1]] if state[1] else None

    return table
Exemplo n.º 3
0
    async def post(self, candidate_id, *args, **kwargs):

        try:
            if not self.current_user.can_vote:
                raise DisableVoting
            async with objects.database.atomic_async():
                candidate = await objects.get(Candidate, id=candidate_id)
                if self.current_user.id == candidate.user_id:
                    raise DisableVoting("不能给自己投票")
                key = f'vote_user_{self.current_user.id}_date_{date.today()}'
                is_vote = redis.get(key)
                if is_vote:
                    raise IsVoteError
                await objects.create(VoteEvent,
                                     vote_id=candidate.vote_id,
                                     voter_id=self.current_user.id,
                                     voter_avatar=self.current_user.avatar,
                                     voter_nickname=self.current_user.nickname,
                                     candidate_id=candidate.id,
                                     reach=1)
                candidate.number_of_votes += 1
                await objects.update(candidate)
                now = datetime.now()
                time_max = datetime.combine(now, time.max)
                expire = int((time_max - now).total_seconds())

                redis.set(key, '1', expire)
            self.finish(
                json.dumps({'number_of_votes': candidate.number_of_votes}))
        except Candidate.DoesNotExist:
            raise NotFoundError("参赛选手未找到")
Exemplo n.º 4
0
    async def post(self, vote_id, *args, **kwargs):

        param = self.request.body.decode("utf-8")
        data = json.loads(param)

        candidate_form = CandidateForm.from_json(data)
        if candidate_form.validate():

            user = self.current_user
            is_new = True if not user.mobile else False
            declaration = candidate_form.declaration.data
            images = candidate_form.images.data

            async with objects.database.atomic_async():

                try:
                    await objects.get(Vote, id=vote_id)
                    if is_new:
                        mobile = candidate_form.mobile.data
                        code = candidate_form.code.data
                        redis_key = "{}_{}".format(mobile, code)
                        if not redis.get(redis_key):
                            raise ErrorCode
                        user.mobile = mobile
                        user.name = candidate_form.name.data
                        await objects.update(user)
                    candidate = await objects.get(Candidate,
                                                  user=user,
                                                  vote_id=vote_id)

                    if not candidate.is_active:
                        raise DisableVoting("您已被禁止参加此次投票!")
                    raise DuplicateError

                except Candidate.DoesNotExist:

                    count = await objects.count(
                        Candidate.select().where(Candidate.vote_id == vote_id))
                    number = "%03d" % (count + 1)
                    candidate = await objects.create(Candidate,
                                                     vote_id=vote_id,
                                                     declaration=declaration,
                                                     cover=images[0],
                                                     number=number,
                                                     user=user)
                    for image in images:
                        await objects.create(CandidateImage,
                                             candidate=candidate,
                                             url=image)

                    self.finish({"candidate_id": candidate.id})

                except Vote.DoesNotExist:

                    raise NotFoundError("投票不存在")
Exemplo n.º 5
0
 async def get_jsapi_ticket(self):
     jsapi_ticket = redis.get('wexin_jsapi_ticket')
     if not jsapi_ticket:
         access_token = await self.get_access_token()
         url = (f'https://api.weixin.qq.com/cgi-bin/ticket/getticket'
                f'?access_token={access_token}&type=jsapi')
         resp = await AsyncHTTPClient().fetch(url)
         content = resp.body.decode("utf-8")
         content = json.loads(content)
         jsapi_ticket = content['ticket']
         redis.set('wexin_jsapi_ticket', jsapi_ticket, 7100)
     return jsapi_ticket
Exemplo n.º 6
0
 async def get_access_token(self):
     access_token = redis.get('wexin_access_token')
     if not access_token:
         url = (
             f'https://api.weixin.qq.com/cgi-bin/token'
             f'?grant_type=client_credential&appid={APPID}&secret={SECRET_KEY}'
         )
         resp = await AsyncHTTPClient().fetch(url)
         content = resp.body.decode("utf-8")
         content = json.loads(content)
         if "errcode" in content:
             from exceptions import WexinError
             raise WexinError(content['errmsg'])
         access_token = content['access_token']
         redis.set('wexin_access_token', access_token, 7100)
     return access_token
Exemplo n.º 7
0
def loads_player(uuid, table):
    raw = redis.get("player:{0}".format(uuid))
    # print "player", uuid, raw
    if not raw:
        return
    data = json.loads(raw)
    player = Player(uuid, None, None, table)
    for k, v in data.items():
        if k in ("table", "session", "machine", "proto"):
            continue
        else:
            player.__dict__[k] = v
    proto = data.get("proto")
    if proto:
        player.proto.__dict__.update(proto)
        player.proto.load()
    state = data["machine"]
    for k, v in player.action_dict.items():
        player.action_dict[int(k)] = v
        del player.action_dict[k]
    player.machine.last_state = player_state[state[0]] if state[0] else None
    player.machine.cur_state = player_state[state[1]] if state[1] else None
    return player
Exemplo n.º 8
0
def loads_player(uuid, table):
    raw = redis.get("player:{0}".format(uuid))
    # print "player", uuid, raw
    if not raw:
        return
    data = pickle.loads(raw)
    player = Player(uuid, None, None, table)
    for k, v in data.items():
        if k in ("table", "session", "machine", "round", "action", "room"):
            continue
        else:
            player.__dict__[k] = v
    state = data["machine"]
    # for k, v in player.action_dict.items():
    #     player.action_dict[int(k)] = v
    #     del player.action_dict[k]
    player.machine.last_state = player_state[state[0]] if state[0] else None
    player.machine.cur_state = player_state[state[1]] if state[1] else None
    player.round.__dict__.update(data["round"])
    player.action.__dict__.update(data["action"])
    player.room.__dict__.update(data["room"])

    return player
Exemplo n.º 9
0
    def enter(self, room_id, player_id, info, user_token, session):
        print "enter room %d" % room_id
        table = self.room_dict.get(room_id)
        if not table:
            if room_id in self.room_settle_cache:
                send(SETTLEMENT_FOR_ROOM_DN, self.room_settle_cache[room_id],
                     session)
                msg_dict = dict()
                msg_dict["code"] = 0
                send(DISMISS_ROOM, msg_dict, session)
            else:
                # 给前端返回房间不存在的错误
                msg_dict = dict()
                msg_dict["code"] = 1
                send(ENTER_ROOM, msg_dict, session)
                print("room {0} not exist, player {1} enter failed".format(
                    room_id, player_id))
            return

        #检测token是否合法
        token = redis.get("token:{0}".format(player_id))

        if token == None or token != user_token:
            msg_dict = dict()
            msg_dict["code"] = 3  #token验证不通过,非法用户
            send(ENTER_ROOM, msg_dict, session)
            table.logger.info("token error: server;{0} client:{1}".format(
                token, user_token))
            return

        if table.room_id != room_id:
            self.room_dict[table.room_id] = table
            del self.room_dict[room_id]
            msg_dict = dict()
            msg_dict["code"] = 1
            send(ENTER_ROOM, msg_dict, session)
            table.logger.fatal(
                "room id map error: msg {0} actually {1}".format(
                    room_id, table.room_id))
            return
        from base.match_mgr import MatchMgr
        player = table.player_dict.get(player_id)
        if player:
            # 服务重启后player没有session
            if player.session:
                if session != player.session:
                    player.table.logger.info(
                        "player {0} cancel old session {1}".format(
                            player_id, player.session.uuid))
                    # SessionMgr().cancel(player.session)
                    player.session.close()
            SessionMgr().register(player, session)
            player.table.logger.info(
                "player {0} register new session {1}".format(
                    player_id, player.session.uuid))
            if player.seat == -1:
                seat = -1
                for seat in range(table.chairs):
                    if seat in table.seat_dict.keys():
                        continue
                    break
                player.seat = seat
            MatchMgr().player_enter(player)
            player.reconnect()
            player.reload_extra()
            player.online_status(True)
        else:
            player = table.lookon_player_dict.get(player_id)
            if player and player.session and session != player.session:
                player.table.logger.info(
                    "player {0} cancel old session {1}".format(
                        player_id, player.session.uuid))
                player.session.close()
            table.enter_room(player_id, info, session)

        Logger().local("ip.log",
                       session.address[0] + ":" + str(session.address[1]))