Ejemplo n.º 1
0
def create_sport_room(msg_dict, session):
    table = TableMgr().create(msg_dict.get("room_id"), msg_dict.get("room_uuid"),
                              "", 0, 0, 0, msg_dict.get("kwargs"), [])
    table.sport_id = msg_dict.get("sport_id")
    players = msg_dict.get("players", [])
    player_tokens = {}
    for p in players:
        player_id = p.get("id")
        info_dict = {"nick": p.get("nick", ""), "icon": p.get("icon", ""), "sex": 1, "game_count": 0, "reg_time": ""}
        info = json.dumps(info_dict, ensure_ascii=False)
        player = Player(player_id, info, None, table)
        from base.state_base.player.init import InitState
        player.machine.trigger(InitState())
        table.lookon_player_dict[player_id] = player
        player.match_score = p.get("score", 0)
        player.is_wait = True
        player.ready()

        token = str(uuid4())
        redis.set("token:{0}".format(player_id), token)
        player_tokens[player_id] = token

    table.dumps()
    table.set_timer("start_10", 10)

    # 发送给Center Server 创建成功的消息
    msg_back = dict()
    msg_back["cmd"] = CG_CREATE_SPORT_ROOM
    msg_back["room_id"] = msg_dict.get("room_id")
    msg_back["state"] = 1
    msg_back["host"] = options.host
    msg_back["port"] = options.server_port
    msg_back["sport_id"] = msg_dict.get("sport_id")
    msg_back["player_tokens"] = player_tokens
    session.send_message(msg_back)  # 发送到游戏服务器
Ejemplo n.º 2
0
 def dumps(self):
     data = {}
     for key, value in self.__dict__.items():
         if key == "table":
             data[key] = value.room_id
         elif key in ("session", "vote_timer"):
             continue
         elif key == "machine":
             data[key] = [None, None]
             if value.last_state:
                 data[key][0] = value.last_state.name
             if value.cur_state:
                 data[key][1] = value.cur_state.name
         elif key == 'award_score':
             data[key] = {k: v for k, v in value.items()}
         elif key == "proto":
             val = self.proto.dump()
             if type(val) is types.StringType:
                 data[key] = unicode(val, errors='ignore')
             else:
                 data[key] = val
         else:
             if type(value) is types.StringType:
                 data[key] = unicode(value, errors='ignore')
             else:
                 data[key] = value
     # print "dumps", data
     redis.set("player:{0}".format(self.uuid), json.dumps(data))
     self.table.dumps()
Ejemplo n.º 3
0
 def dumps(self):
     data = {}
     for key, value in self.__dict__.items():
         if key in ("logger", "conf", "request"):
             continue
         elif key == "player_dict":
             data[key] = value.keys()
         elif key == "temp_timer":
             data[key] = []
         elif key == "seat_dict":
             data[key] = {k: v.uuid for k, v in value.items()}
         elif key == "reward_info":
             data[key] = {k: v for k, v in value.items()}
         elif key == "com_dict":
             data[key] = {k: v.uuid for k, v in value.items()}
         elif key == "machine":
             data[key] = [None, None]
             if value.cur_state:
                 data[key][1] = value.cur_state.name
             if value.last_state:
                 data[key][0] = value.last_state.name
         else:
             data[key] = value
             # print "table dumps", data
     redis.set("table:{0}".format(self.room_id), json.dumps(data))
Ejemplo n.º 4
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("参赛选手未找到")
Ejemplo 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
Ejemplo 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
Ejemplo n.º 7
0
 def dumps(self):
     data = {}
     for key, value in self.__dict__.items():
         if key == "table":
             data[key] = value.room_id
         elif key in ("session", "vote_timer"):
             continue
         elif key == "machine":
             data[key] = [None, None]
             if value.last_state:
                 data[key][0] = value.last_state.name
             if value.cur_state:
                 data[key][1] = value.cur_state.name
         elif key in ("round", "action", "room"):
             data[key] = value.dumps()
         else:
             data[key] = value
     redis.set("player:{0}".format(self.uuid), pickle.dumps(data))
     self.table.dumps()
Ejemplo n.º 8
0
 def dumps(self):
     self.logger.info("table state: {0}".format(self.state))
     data = {}
     for key, value in self.__dict__.items():
         if key in ("logger", "conf", "request", "lookon_player_dict"):
             continue
         elif key == "player_dict":
             data[key] = value.keys()
         elif key == "seat_dict":
             data[key] = {k: v.uuid for k, v in value.items()}
         elif key == "machine":
             data[key] = [None, None]
             if value.cur_state:
                 data[key][1] = value.cur_state.name
             if value.last_state:
                 data[key][0] = value.last_state.name
         else:
             data[key] = value
     redis.set("table:{0}".format(self.room_id), pickle.dumps(data))
Ejemplo n.º 9
0
    async def post(self, *args, **kwargs):

        ret = {}

        param = self.request.body.decode("utf-8")
        param = json.loads(param)
        sms_form = SmsCodeForm.from_json(param)
        if sms_form.validate():
            mobile = sms_form.mobile.data
            code = generate_code()

            re_json = await yunpian.send_single_sms(code, mobile)
            if re_json["code"] != 0:
                self.set_status(400)
                ret["mobile"] = re_json["msg"]
            else:
                redis.set(f"{mobile}_{code}", 1, 10 * 60)
        else:
            self.set_status(400)
            for field in sms_form.errors:
                ret[field] = sms_form.errors[field][0]

        self.finish(ret)
Ejemplo n.º 10
0
def user_token(msg_dict, session):
    redis.set("token:{0}".format(msg_dict.get("user_id")), msg_dict.get("token"))   # 存缓存里,服务重启不会丢失