Skip to content

Commit

Permalink
Update client to phaser3
Browse files Browse the repository at this point in the history
  • Loading branch information
mailgyc committed Jun 6, 2020
1 parent bc76024 commit 5e7db45
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 20 deletions.
Empty file.
85 changes: 85 additions & 0 deletions doudizhu/apps/social/message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
from __future__ import annotations

import time
from typing import Optional
from xml.etree import ElementTree
from xml.etree.ElementTree import Element


class Msg(object):

@staticmethod
def parse_xml(data: str) -> Optional[Msg]:
if len(data) == 0:
return None
xml = ElementTree.fromstring(data)
msg_type = xml.find('MsgType').text

factory = {'text': TextMsg, 'image': ImageMsg}
return factory.get(msg_type).from_xml(xml)

def __init__(self, *args, **kwargs):
self.ToUserName = None
self.FromUserName = None
self.CreateTime = None
self.MsgType = None
self.MsgId = None

def from_xml(self, xml: Element):
self.ToUserName = xml.find('ToUserName').text
self.FromUserName = xml.find('FromUserName').text
self.CreateTime = xml.find('CreateTime').text
self.MsgType = xml.find('MsgType').text
self.MsgId = xml.find('MsgId').text
return self

def to_xml(self, *args, **kwargs):
pass

@property
def timestamp(self):
return int(time.time())


class TextMsg(Msg):

def __init__(self):
super().__init__()
self.Content = None

def from_xml(self, xml: Element):
super().from_xml(xml)
self.Content = xml.find('Content').text.encode("utf-8")
return self

def to_xml(self, content):
return f"""<xml>
<ToUserName><![CDATA[{self.FromUserName}]]></ToUserName>
<FromUserName><![CDATA[{self.ToUserName}]]></FromUserName>
<CreateTime>{self.timestamp}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{content}]]></Content>
</xml>"""


class ImageMsg(Msg):
def __init__(self):
super().__init__()
self.PicUrl = None
self.MediaId = None

def from_xml(self, xml: Element):
self.PicUrl = xml.find('PicUrl').text
self.MediaId = xml.find('MediaId').text
return self

def to_xml(self, media):
return f"""<xml>
<ToUserName><![CDATA[{self.FromUserName}]]></ToUserName>
<FromUserName><![CDATA[{self.ToUserName}]]></FromUserName>
<CreateTime>{self.timestamp}</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[{media}]]></MediaId>
</Image>
</xml>"""
26 changes: 7 additions & 19 deletions doudizhu/apps/social/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@
from apps.game.storage import Storage
from contrib.db import AsyncConnection
from contrib.handlers import JwtMixin
from settings import WECHAT_CONFIG
from .message import Msg

logger = logging.getLogger(__name__)

APPID = 'wx48e8704e3acdbb9d'
APPSECRET = 'd549ac4edb0a3c835264398886d4feff'
appid = WECHAT_CONFIG['appid']
appsecret = WECHAT_CONFIG['appsecret']


class WechatConfig(RequestHandler):
# url = https://m.ihouser.com/social/config
token = '0re7LejEZ05ydfck'
encoding_aes_key = '73SVvJPl0nvQMIcdHLv6OrcJLq9anjd2FaFrNngZwOf'
token = WECHAT_CONFIG['token']
encoding_aes_key = WECHAT_CONFIG['encoding_aes_key']

def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
pass
Expand Down Expand Up @@ -67,7 +67,7 @@ async def get(self):
if code is None:
self.clear_cookie('social')
redirect = self.origin + '/social/index'
url = f'https://open.weixin.qq.com/connect/oauth2/authorize?appid={APPID}&redirect_uri={redirect}&response_type=code&scope=snsapi_userinfo#wechat_redirect'
url = f'https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirect}&response_type=code&scope=snsapi_userinfo#wechat_redirect'
self.redirect(url)
else:
# 1. 从数据库获取用户信息
Expand Down Expand Up @@ -130,26 +130,14 @@ async def fetch_access_token(code: str):
:param code:
:return:
"""
url = f'https://api.weixin.qq.com/sns/oauth2/access_token?appid={APPID}&secret={APPSECRET}&code={code}&grant_type=authorization_code'
url = f'https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={appsecret}&code={code}&grant_type=authorization_code'
r = await async_http(url)
return r.get('access_token'), r.get('openid'), r.get('unionid')

@staticmethod
async def fetch_userinfo(access_token, openid) -> Dict[str, Union[int, str]]:
"""
第四步:拉取用户信息(需scope为 snsapi_userinfo)
{
'openid': 'o5Nrmv3dX2E4UO4dv4y8AMgJWcB8',
'nickname': '懿字尾',
'sex': 1,
'language': 'zh_CN',
'city': '广州',
'province': '广东',
'country': '中国',
'headimgurl': 'http://thirdwx.qlogo.cn/mmopen/vi_32/55lYKUdcPFgUHibRYmaRiaBVamhPRiawsGZKVG6xxkdSia6/132',
'privilege': [],
'unionid': 'orfFiw6XM0zO3OE9Iug5lqga9l_o'
}
:param access_token:
:param openid:
:return:
Expand Down
8 changes: 7 additions & 1 deletion doudizhu/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@

PORT = os.getenv('PORT', 8080)

WECHAT_CONFIG = {
'appid': os.getenv('APPID'),
'appsecret': os.getenv('APPSECRET'),
'token': os.getenv('TOKEN'),
'encoding_aes_key': os.getenv('ENCODING_AES_KEY'),
}


def database_url(url):
from urllib.parse import urlparse, ParseResult
Expand Down Expand Up @@ -54,7 +61,6 @@ def database_url(url):
}
}


if os.getenv('SENTRY_DSN'):
import sentry_sdk
from sentry_sdk.integrations.tornado import TornadoIntegration
Expand Down

0 comments on commit 5e7db45

Please sign in to comment.