def create_new_platform(user_id): # 成为平台属主 user = User.get(user_id=user_id) assert user account = Account.get(user_id=user.user_id, platform_id=user.bind_platform_id) assert account platform = Platform.get(owner_user_id=user.user_id) if not platform: # SELECT `AUTO_INCREMENT` FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'trade' AND table_name = 'platform'; # ALTER TABLE `platform` AUTO_INCREMENT = 3; platform = Platform.create(owner_user_id=user.user_id) platform.platform_id = platform.id qrcode_info = WeClient.create_qrcode(scene_str=str(platform.platform_id), is_permanent=True) log.d(f'qrcode_info: {qrcode_info}') qrcode_content = qrcode_info['url'] log.i( f'create qrcode, platform_id: {platform.platform_id}, qrcode_content: {qrcode_content}' ) platform.update(qrcode_content=qrcode_content, platform_id=platform.id, ssid=f'WIFI-{platform.platform_id}') user.update(bind_platform_id=platform.platform_id) account.update(role=Account.Role.PLATFORM_OWNER.value, platform_id=user.bind_platform_id) return platform
def __init__(self): # FIXME: This function is massive. Break it up self._test_map = {} platform_id_map = {} branch_id_map = {} for test in Test.all(): if test.hidden: continue branch_ids = [Branch.get(branch_key).id for branch_key in test.branches] platform_ids = [Platform.get(platform_key).id for platform_key in test.platforms] self._test_map[test.id] = { 'name': test.name, 'branchIds': branch_ids, 'platformIds': platform_ids, } for platform_id in platform_ids: platform_id_map.setdefault(platform_id, {'tests': [], 'branches': []}) platform_id_map[platform_id]['tests'].append(test.id) platform_id_map[platform_id]['branches'] += branch_ids for branch_id in branch_ids: branch_id_map.setdefault(branch_id, {'tests': [], 'platforms': []}) branch_id_map[branch_id]['tests'].append(test.id) branch_id_map[branch_id]['platforms'] += platform_ids self._platform_map = {} for platform in Platform.all(): if platform.id not in platform_id_map: continue if platform.hidden: for test_id in platform_id_map[platform.id]['tests']: self._test_map[test_id]['platformIds'].remove(platform.id) for branch_id in platform_id_map[platform.id]['branches']: branch_id_map[branch_id]['platforms'].remove(platform.id) continue self._platform_map[platform.id] = { 'name': platform.name, 'testIds': list(set(platform_id_map[platform.id]['tests'])), 'branchIds': list(set(platform_id_map[platform.id]['branches'])), } self._branch_map = {} for branch in Branch.all(): if branch.id not in branch_id_map: continue self._branch_map[branch.id] = { 'name': branch.name, 'testIds': list(set(branch_id_map[branch.id]['tests'])), 'platformIds': list(set(branch_id_map[branch.id]['platforms'])), }
def get(self): self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'; cache = memcache.get('manifest') if cache: self.response.out.write(cache) return testMap = {} platformIdMap = {} branchIdMap = {} for test in Test.all(): branchIds = [Branch.get(branchKey).id for branchKey in test.branches] platformIds = [Platform.get(platformKey).id for platformKey in test.platforms] testMap[test.id] = { 'name': test.name, 'branchIds': branchIds, 'platformIds': platformIds, } for platformId in platformIds: platformIdMap.setdefault(platformId, {'tests': [], 'branches': []}) platformIdMap[platformId]['tests'].append(test.id) platformIdMap[platformId]['branches'] += branchIds for branchId in branchIds: branchIdMap.setdefault(branchId, {'tests': [], 'platforms': []}) branchIdMap[branchId]['tests'].append(test.id) branchIdMap[branchId]['platforms'] += platformIds platformMap = {} for platform in Platform.all(): if platform.id not in platformIdMap: continue platformMap[platform.id] = { 'name': platform.name, 'testIds': list(set(platformIdMap[platform.id]['tests'])), 'branchIds': list(set(platformIdMap[platform.id]['branches'])), } branchMap = {} for branch in Branch.all(): if branch.id not in branchIdMap: continue branchMap[branch.id] = { 'name': branch.name, 'testIds': list(set(branchIdMap[branch.id]['tests'])), 'platformIds': list(set(branchIdMap[branch.id]['platforms'])), } result = json.dumps({'testMap': testMap, 'platformMap': platformMap, 'branchMap': branchMap}) self.response.out.write(result) memcache.add('manifest', result)
def get(self): self.response.headers["Content-Type"] = "text/plain; charset=utf-8" self.response.out.write('{"testMap":') testMap = {} platformIdMap = {} branchIdMap = {} for test in Test.all(): branchIds = [Branch.get(branchKey).id for branchKey in test.branches] platformIds = [Platform.get(platformKey).id for platformKey in test.platforms] testMap[test.id] = {"name": test.name, "branchIds": branchIds, "platformIds": platformIds} for platformId in platformIds: platformIdMap.setdefault(platformId, {"tests": [], "branches": []}) platformIdMap[platformId]["tests"].append(test.id) platformIdMap[platformId]["branches"] += branchIds for branchId in branchIds: branchIdMap.setdefault(branchId, {"tests": [], "platforms": []}) branchIdMap[branchId]["tests"].append(test.id) branchIdMap[branchId]["platforms"] += platformIds self.response.out.write(json.dumps(testMap)) self.response.out.write(',"platformMap":') platformMap = {} for platform in Platform.all(): if platform.id not in platformIdMap: continue platformMap[platform.id] = { "name": platform.name, "testIds": list(set(platformIdMap[platform.id]["tests"])), "branchIds": list(set(platformIdMap[platform.id]["branches"])), } self.response.out.write(json.dumps(platformMap)) self.response.out.write(',"branchMap":') branchMap = {} for branch in Branch.all(): if branch.id not in branchIdMap: continue branchMap[branch.id] = { "name": branch.name, "testIds": list(set(branchIdMap[branch.id]["tests"])), "platformIds": list(set(branchIdMap[branch.id]["platforms"])), } self.response.out.write(json.dumps(branchMap)) self.response.out.write("}")
def increase_user_resource(total_fee: int, out_trade_no: str, transaction_id: str, attach: str): # 根据out_trade_no检查数据库订单 order = Order.get(out_trade_no=out_trade_no) assert order assert not order.is_paid() account = Account.get(user_id=order.user_id, platform_id=order.platform_id) assert account # 计算时长叠加 tariff = Tariff.attach_to_tariff(attach) before = account.expired_at after = tariff.increase_duration(before) with transaction.atomic(): # 变更免费资源 account.update(expired_at=after) # 变更订单状态 和 微信订单号 order.update(status=Order.Status.PAID.value, transaction_id=transaction_id) # 插入免费资源历史变更表 ResourceChange.create(user_id=account.user_id, out_trade_no=order.out_trade_no, before=before, after=after) log.i( f"UPDATE orders SET status = '{order.status}', transaction_id = '{transaction_id}' WHERE out_trade_no = '{out_trade_no}'" ) # 公众号消息通知owner platform = Platform.get(platform_id=account.platform_id) user = User.get(user_id=account.user_id) owner = User.get(user_id=platform.owner_user_id) WePush.notify_owner_order_paid(platform_id=platform.platform_id, openid=owner.openid, total_fee=order.total_fee, nickname=user.nickname, paid_at=order.updated_at, trade_no=out_trade_no)
def __init__(self): # FIXME: This function is massive. Break it up self._test_map = {} platform_id_map = {} branch_id_map = {} for test in Test.all(): if test.hidden: continue branch_ids = [ Branch.get(branch_key).id for branch_key in test.branches ] platform_ids = [ Platform.get(platform_key).id for platform_key in test.platforms ] self._test_map[test.id] = { 'name': test.name, 'branchIds': branch_ids, 'platformIds': platform_ids, } for platform_id in platform_ids: platform_id_map.setdefault(platform_id, { 'tests': [], 'branches': [] }) platform_id_map[platform_id]['tests'].append(test.id) platform_id_map[platform_id]['branches'] += branch_ids for branch_id in branch_ids: branch_id_map.setdefault(branch_id, { 'tests': [], 'platforms': [] }) branch_id_map[branch_id]['tests'].append(test.id) branch_id_map[branch_id]['platforms'] += platform_ids self._platform_map = {} for platform in Platform.all(): if platform.id not in platform_id_map: continue if platform.hidden: for test_id in platform_id_map[platform.id]['tests']: self._test_map[test_id]['platformIds'].remove(platform.id) for branch_id in platform_id_map[platform.id]['branches']: branch_id_map[branch_id]['platforms'].remove(platform.id) continue self._platform_map[platform.id] = { 'name': platform.name, 'testIds': list(set(platform_id_map[platform.id]['tests'])), 'branchIds': list(set(platform_id_map[platform.id]['branches'])), } self._branch_map = {} for branch in Branch.all(): if branch.id not in branch_id_map: continue self._branch_map[branch.id] = { 'name': branch.name, 'testIds': list(set(branch_id_map[branch.id]['tests'])), 'platformIds': list(set(branch_id_map[branch.id]['platforms'])), }
def get_reply_msg(): # 被动回复 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Passive_user_reply_message.html if isinstance(msg, SubscribeScanEvent) or isinstance( msg, ScanEvent): # 未关注用户扫描带参数二维码事件 - 订阅关注 # 已关注用户扫描带参数二维码事件 platform_id = int(msg.scene_id) platform = Platform.get(platform_id=platform_id) assert platform user = User.get(openid=from_user_openid) if not user: # 创建 user user = User.create(openid=from_user_openid, bind_platform_id=platform.platform_id) else: # user 表记录, 存在 if user.bind_platform_id != platform.platform_id: log.w( f'platform_id change: {user.bind_platform_id} -> {platform.platform_id}, openid: {user.openid}' ) user.update(bind_platform_id=platform.platform_id) account = Account.get(user_id=user.user_id, platform_id=user.bind_platform_id) if not account: # 创建 account username = MyRandom.random_digit(length=8) expired_at = Datetime.localtime() + datetime.timedelta( days=1) # 新账户一天内免费 account = Account.create( user_id=user.user_id, platform_id=user.bind_platform_id, username=username, password=username, radius_password=username, role=Account.Role.PAY_USER.value, expired_at=expired_at, ) sentry_sdk.capture_message( f'有用户扫描带参数二维码, platform_id: {platform.platform_id}, openid: {from_user_openid}' ) # 判断是否允许房东注册 if platform.platform_id == settings.ADMIN_PLATFORM_ID: redis = get_redis() if redis.get('enable_platform_register'): # 新创建平台 new_platform = create_new_platform( user_id=user.user_id) platform_url = f'{settings.API_SERVER_URL}/platform/{new_platform.platform_id}' sentry_sdk.capture_message( f'房东平台已建立, platform_url: {platform_url}') redis.delete('enable_platform_register') # 应答 return TextReply( source=appid, target=from_user_openid, content= f'账号: {account.username}\n密码: {account.password}\n状态: {account.status}' ) if isinstance(msg, ClickEvent): # 点击按钮 - 账号中心 if msg.key == WeClient.ACCOUNT_VIEW_BTN_EVENT: user = User.get(openid=from_user_openid) if not user or user.bind_platform_id is None: # 用户未经扫码, 进入公众号 return TextReply(source=appid, target=from_user_openid, content=f'请先扫描房东的WIFI二维码') else: platform = Platform.get( platform_id=user.bind_platform_id) if platform.is_platform_owner( user_id=user.user_id ) and not settings.is_admin(openid=from_user_openid): # 房东不能打开充值页面, 但 admin 可以 return TextReply(source=appid, target=from_user_openid, content=f'房东不允许打开充值页面') r = ArticlesReply(source=appid, target=from_user_openid) r.add_article({ 'title': f'点击进入', 'description': '查询WIFI密码 / WIFI续费', 'image': 'http://zlxpic.lynatgz.cn/zhuzaiyuan_mini.jpg', 'url': WeClient.ACCOUNT_VIEW_URI, }) return r elif msg.key == WeClient.CUSTOMER_SERVICE_BTN_EVENT: return TextReply(source=appid, target=from_user_openid, content=settings.MP_DEFAULT_REPLY) elif isinstance(msg, SubscribeEvent): # 关注公众号事件 pass elif isinstance(msg, TextMessage): # 文本消息 if msg.content in ['help', '帮助', '命令']: command = [ 'id', '搜索 $name', 'free', '放通mac', '房东注册', ] message = '命令:\n ' + '\n '.join(command) return TextReply(source=appid, target=from_user_openid, content=message) elif msg.content == 'id': # 查看用户ID user = User.get(openid=from_user_openid) messages = [ f'你的信息:', f'openid: {user.openid}', f'user_id: {user.user_id}', ] return TextReply(source=appid, target=from_user_openid, content='\n'.join(messages)) # 以下命令需要 admin 权限 elif msg.content.startswith('搜索') and settings.is_admin( openid=from_user_openid): # 搜索用户信息 name = msg.content.split('搜索')[1].strip() return TextReply( source=appid, target=from_user_openid, content= f'{settings.API_SERVER_URL}/search/user?name={name}') elif msg.content.startswith('放通mac') and settings.is_admin( openid=from_user_openid): redis = get_redis() ex = 60 * 5 redis.set('enable_mac_authentication', str(datetime.datetime.now()), ex=ex) return TextReply(source=appid, target=from_user_openid, content=f'有效时间: {ex}秒') elif msg.content.startswith('房东注册') and settings.is_admin( openid=from_user_openid): redis = get_redis() ex = 60 * 5 redis.set('enable_platform_register', str(datetime.datetime.now()), ex=ex) return TextReply(source=appid, target=from_user_openid, content=f'有效时间: {ex}秒') elif msg.content.startswith('free') and settings.is_admin( openid=from_user_openid): expired_at = Datetime.localtime() + datetime.timedelta( minutes=30) account = Account.get(user_id=0, platform_id=0) if not account: account = Account.create( user_id=0, platform_id=0, username='******', password='******', radius_password='******', role=Account.Role.FREE_USER.value, expired_at=expired_at, ) else: account.update(expired_at=expired_at) content = f'用户名: {account.username}, 密码: {account.password}, 失效时间: {Datetime.to_str(expired_at, fmt="%Y-%m-%d %H:%M:%S")}' return TextReply(source=appid, target=from_user_openid, content=content) else: return TextReply(source=appid, target=from_user_openid, content=settings.MP_DEFAULT_REPLY) return None
def get(self, request, platform_id): platform = Platform.get(platform_id=platform_id) data = {} if platform: data = platform.to_dict() return BihuResponse(data=data)