def get_user_info(): user = get_current_user(g.user_id) if user is None: log.warn("当前user_id没有获得用户信息: {}".format(g.user_id)) return fail(HTTP_OK, u'没有当前用户信息') if user.deleted: log.warn("当前user_id用户已经被删除: {}".format(g.user_id)) return fail(HTTP_OK, u'当前用户已经被删除') # 判断昵称或头像是否已经获取到了 if user.head_img_url == '' or user.nick_name == '': # 先判断token是否存在 subscribe, nick_name, head_img_url = get_wechat_user_info(user.openid) if head_img_url == '' or nick_name == '': log.error( "再次更新用户ID = {} 头像与昵称失败: head_img_url = {} nick_name = {}". format(user.id, head_img_url, nick_name)) else: # 存储用户昵称和头像信息 if UserService.save_nick_and_head(user, nick_name, head_img_url): log.info( "重新更新用户昵称与头像成功: user_id = {} head = {} nike = {}".format( user.id, user.head_img_url, user.nick_name)) # # 存储用户信息 # user.head_img_url = head_img_url # user.nick_name = nick_name # if user.save(): # log.info("重新更新用户昵称与头像成功: user_id = {} head = {} nike = {}".format( # user.id, user.head_img_url, user.nick_name)) return success(user.to_dict())
def get_update_state(device_code): if isinstance(device_code, Device): return device_code.update_state if isinstance(device_code, basestring): device_update_key = RedisClient.get_device_update_status_key( device_code) update_state = redis_device_client.get(device_update_key) if update_state is not None: return update_state log.info("当前设备游戏更新状态还未缓存: device_code = {}".format(device_code)) device = DeviceService.get_device_by_code(device_code) if device is None: log.error( "当前设备号没有搜索到设备信息: device_code = {}".format(device_code)) return None # 缓存游戏更新设备状态 redis_device_client.setex(device_update_key, DEFAULT_EXPIRED_DEVICE_STATUS, device.update_state) return device.update_state log.error("当前参数既不是字符串类型也不是Device类型: type = {}".format( type(device_code))) return None
def set_update_state(device, update_state, last_update_time=None): # 如果传出的是 设备号 则查找 if isinstance(device, basestring): device = DeviceService.get_device_by_code(device) if device is None: return False update_info = {Device.update_state: update_state} if last_update_time is not None: update_info[Device.last_update_time] = last_update_time rowcount = Device.query.filter_by(id=device.id).update(update_info) if rowcount <= 0: log.error("设备游戏更新状态更新失败: device_id = {} update_state = {}".format( device.id, update_state)) return False log.info("设备更新状态写入数据库完成: rowcount = {} ".format(rowcount)) device_update_key = RedisClient.get_device_update_status_key( device.device_code) # 存储状态到redis中 状态只保存一天,防止数据被删除 缓存一直存在 redis_device_client.setex(device_update_key, DEFAULT_EXPIRED_DEVICE_STATUS, update_state) log.info( "设备更新状态设置成功: device_id = {} device_code = {} update_state = {}". format(device.id, device.device_code, update_state)) return True
def update_game(): log.info("开始后台更新游戏...") if DeviceGameService.update_game_all_by_http(): log.info("游戏更新成功!") else: log.error("游戏更新失败!") log.info("后台更新游戏完成...")
def device_game_add(): if not request.is_json: log.warn("参数错误...") return fail(HTTP_OK, u"need application/json!!") username = request.json.get('username') password = request.json.get('password') name = request.json.get('game') version = request.json.get('version') if not isinstance(name, basestring) or not isinstance(version, basestring): log.error( "参数错误: username = {} password = {} game = {} version = {}".format( username, password, name, version)) return fail(HTTP_OK, u"参数错误") # 先判断能否登录 is_success, msg = AdminService.verify_authentication(username, password) if not is_success: return fail(HTTP_OK, msg) # 开始更新游戏信息 if not DeviceGameService.add_device_game(name, version): return fail(HTTP_OK, u"游戏更新失败,请重试!") return success(u'游戏更新成功!')
def update(device_id): if isinstance(device_id, Device): device = device_id else: device = Device.get(device_id) if device is None: log.error("当前设备不存在,或者参数错误: device_id = {}".format(device_id)) return False if DeviceService.get_update_state( device) != DeviceUpdateStatus.UPDATE_FINISH: log.info( "当前设备游戏更新状态不需要设置: device_id = {} update_state = {}".format( device.id, device.update_state)) return True # 判断是否有游戏需要更新 if not DeviceGameService.is_device_need_update(device.id): log.info("当前游戏都是最新版, 不需要更新: device_id = {}".format(device.id)) return True log.info("当前存在游戏需要更新,通知客户端更新: device_id = {}".format(device.id)) return DeviceService.set_update_state(device, DeviceUpdateStatus.UPDATE_WAIT)
def deploy_device_game(device): # 先获得所有游戏 game_list = GameListService.get_game_list() log.info("当前需要部署的设备: device_id = {}".format(device.id)) # 添加游戏 for name, version in game_list: game, is_success = DeviceGameService.add(device.id, name, version) if is_success: log.info("当前设备 游戏 添加成功: device_id = {} game = {} version = {}". format(device.id, name, version)) else: log.error( "当前设备 游戏 添加失败: device_id = {} game = {} version = {}". format(device.id, name, version)) # 设置当前游戏为等待更新 if DeviceGameService.update(device): log.info("当前设备更新状态设置成功: device_id = {} update_state = {}".format( device.id, device.update_state)) else: log.error("当前设备更新状态设置失败: device_id = {} update_state = {}".format( device.id, device.update_state)) log.info("当前设备游戏部署完成: device_id = {}".format(device.id))
def create(user_id, amount, transaction_id, pay_time): amount = int(amount) user_id = int(user_id) recharge = Recharge(user_id=user_id, amount=amount, transaction_id=transaction_id, pay_time=pay_time) # 账户总额增加 user = User.get(user_id) if user is None: log.warn("当前充值用户信息不存在: user_id = {}".format(user_id)) return None, False try: user.balance_account += amount user.total_account += amount user.utime = datetime.now() db.session.add(user) db.session.add(recharge) db.session.commit() # 发送充值成功通知 TemplateService.recharge_remind(user.openid, pay_time, amount) except IntegrityError: log.error("主键重复: user_id = {} amount = {}".format(user_id, amount)) db.session.rollback() return None, False except Exception as e: log.error("未知插入错误: user_id = {} amount = {}".format( user_id, amount)) log.exception(e) return None, False return recharge, True
def access_token_thread(): log.info("开始启动缓存刷新线程...") # 30秒轮询一次 SLEEP_TIME = 30 while True: try: ttl = cache_client.ttl(WECHAT_ACCESS_TOKEN_KEY) log.info("当前key存活时间: key = {} ttl = {}".format( WECHAT_ACCESS_TOKEN_KEY, ttl)) if ttl <= WX_CACHE_LAST_TIME: log.info("开始获取token...") update_access_token() log.info("获取token结束...") ttl = cache_client.ttl(WECHAT_JSAPI_TICKET_KEY) log.info("当前key存活时间: key = {} ttl = {}".format( WECHAT_JSAPI_TICKET_KEY, ttl)) if ttl <= WX_CACHE_LAST_TIME: log.info("开始获取jsapi_ticket...") update_ticket() log.info("获取jsapi_ticket结束...") except Exception as e: log.error("缓存程序异常:") log.exception(e) time.sleep(SLEEP_TIME)
def get_role_list(): ''' page: 当前页码 size: 每页读取数目, 最大不超过50项 ''' if not request.is_json: log.warn("参数错误...") return fail(HTTP_OK, u"need application/json!!") page = request.json.get('page') size = request.json.get('size') if not isinstance(page, int) or \ not isinstance(size, int): log.warn("请求参数错误: page = {} size = {}".format(page, size)) return fail(HTTP_OK, u"请求参数错误") # 请求参数必须为正数 if page <= 0 or size <= 0: msg = "请求参数错误: page = {} size = {}".format(page, size) log.error(msg) return fail(HTTP_OK, msg) if size > 50: log.info("翻页最大数目只支持50个, 当前size超过50 size = {}!".format(size)) size = 50 return success(Role.find_role_list(page, size))
def create(username, password, name, address_id=Maintain.ALL_ADDRESS_ID): # 如果地址信息不正确,则选用所有地址可用 if Address.get(address_id) is None: log.warn("当前传入地址ID没有找到相应地址信息,默认调整为全部地区: address_id = {}".format( address_id)) address_id = Maintain.ALL_ADDRESS_ID maintain = Maintain(username=username, name=name, address_id=address_id) maintain.password = password try: db.session.add(maintain) db.session.commit() except IntegrityError: log.error("主键重复: username = {} name = {} address_id = {}".format( username, name, address_id)) db.session.rollback() return None, False except Exception as e: log.error("未知插入错误: username = {} name = {} address_id = {}".format( username, name, address_id)) log.exception(e) return None, False return maintain, True
def update_game(): if not request.is_json: log.warn("参数错误...") return fail(HTTP_OK, u"need application/json!!") game = request.json.get('game') version = request.json.get('version') md5 = request.json.get('md5') if not isinstance(game, basestring) or \ not isinstance(version, basestring) or \ not isinstance(md5, basestring): log.error("参数错误: game = {} version = {} md5 = {}".format( game, version, md5)) return fail(HTTP_OK, u"参数错误") # 更新游戏列表 if not GameListService.update_game_list(game, version): return fail(HTTP_OK, u"更新游戏列表失败!") game_manage = GameVersionManageService.get_game_info(game, version) if game_manage is None: game_manage, is_success = GameVersionManageService.create( game, version, md5) if not is_success: return fail(HTTP_OK, u"游戏更新失败,请重试!") else: if not GameVersionManageService.update_game_info(game_manage, md5): return fail(HTTP_OK, u"游戏更新失败,请重试!") # 开始更新游戏信息 if not DeviceGameService.add_device_game(game, version): return fail(HTTP_OK, u"游戏更新失败,请重试!") return success(u'游戏更新成功!')
def online( cls, openid, # 上线时间 self.ctime ctime, # 地址 结构体对象 address, # 余额 分 balance, # 计费 价格 分钟 / 分 charge_mode): access_token = redis_cache_client.get(WECHAT_ACCESS_TOKEN_KEY) if access_token is None: log.error("access_token 为None,刷新token进程异常!!!") return online_time = ctime.strftime('%Y-%m-%d %H:%M:%S') address_str = address.get_full_address() account_url = url_for("wechat.menu", name="account", _external=True) log.info("当前用户中心地址: url = {}".format(account_url)) if WechatTemplate.online(access_token, openid, online_time, address_str, balance, charge_mode, url=account_url): log.info("发送微信上机通知成功: openid = {}".format(openid)) else: log.warn("发送微信上机通知失败: openid = {}".format(openid))
def get_current_time_charging(charging_str): try: charge_dict = json.loads(charging_str) charge_dict['cur_time'] = get_now_time() return charge_dict except Exception as e: log.error("json转换失败: charging = {}".format(charging_str)) log.exception(e) return {'error': '计费json数据格式转换失败', 'status': -1}
def delete_game_list(game): try: game_list = GameList.query.filter_by(game=game).first() if game_list is not None: db.session.delete(game_list) db.session.commit() except Exception as e: log.error("删除游戏失败:") log.exception(e)
def do_offline_order_by_device_code(device_code): device_code_key = RedisClient.get_device_code_key(device_code) record_key = redis_cache_client.get(device_code_key) if record_key is None: log.error("当前通过device_code = {} 下机失败, 没有在redis中找到对应的上机信息".format( device_code)) return False # 发送下机指令 return WindowsService.do_offline_order(record_key)
def delete_game(game): try: game_list = GameVersionManage.query.filter_by(game=game).all() [db.session.delete(game_item) for game_item in game_list] db.session.commit() except Exception as e: log.error("删除游戏失败:") log.exception(e) return False return True
def get_game_list(): result_list = [] try: game_list = GameList.query.all() for game_item in game_list: result_list.append([game_item.game, game_item.version]) except Exception as e: log.error("获取最新游戏列表失败:") log.exception(e) return result_list
def recharge_remind(cls, openid, pay_time, account): access_token = redis_cache_client.get(WECHAT_ACCESS_TOKEN_KEY) if access_token is None: log.error("access_token 为None,刷新token进程异常!!!") return recharge_time = pay_time.strftime('%Y-%m-%d %H:%M:%S') if WechatTemplate.recharge_remind(access_token, openid, recharge_time, account): log.info("发送微信充值通知成功: openid = {}".format(openid)) else: log.warn("发送微信充值通知失败: openid = {}".format(openid))
def delete(self): try: db.session.delete(self) db.session.commit() except Exception as e: db.session.rollback() log.error("未知删除错误: {}".format( json.dumps(self.to_dict(), ensure_ascii=False))) log.exception(e) return False return True
def save(self): self.utime = datetime.now() try: db.session.add(self) db.session.commit() except Exception as e: db.session.rollback() log.error("未知存储错误: {}".format( json.dumps(self.to_dict(), ensure_ascii=False))) log.exception(e) return False return True
def delete(self): try: db.session.delete(self) self.address.device_num -= 1 if self.address.device_num >= 1 else 0 db.session.add(self.address) db.session.commit() except Exception as e: db.session.rollback() log.error("未知删除错误: {}".format( json.dumps(self.to_dict(), ensure_ascii=False))) log.exception(e) return False return True
def do_offline_order(record_key): url = 'http://localhost:8080/windows/logout' try: r = requests.post(url, json={'token': record_key}, timeout=10) log.info("当前处理状态status_code = {}".format(r.status_code)) log.info("当前处理返回信息: {}".format(r.content)) if r is not None and r.status_code == 200: return True except Exception as e: log.error("发送下机指令异常: ") log.exception(e) return False
def get_proxy(): if not request.is_json: log.warn("参数错误...") return fail() # { # 'username': '******', # 'password': '******', # 'type': 'static' or 'dynamic' // 这个参数保留,目前不一定用 # } username = request.json.get('username') password = request.json.get('password') if not isinstance(username, basestring): log.error("用户错误,不是字符串: username = {} type = {}".format(username, type(username))) return fail('用户名类型错误!') if not isinstance(password, basestring): log.error("密码错误,不是字符串: password = {} type = {}".format(password, type(password))) return fail('密码类型错误!') # 判断当前用户是否在redis中 origin_password = redis.get(username) if origin_password is None: log.error("当前用户不存在: username = {} password = {}".format(username, password)) return fail('当前用户不存在!') if origin_password != password: log.error("密码错误: username = {} password = {}".format(username, password)) return fail('密码错误!') # 请求动态代理服务 proxy = get_dynamic_proxy(LOCAL_HOST) return success(proxy)
def save_nick_and_head(user, nick_name, head_img_url): if user is None or nick_name is None or head_img_url is None: log.error("存储参数异常: user = {} nick_name = {} head_img_url = {}".format( user, nick_name, head_img_url)) return False if nick_name == '' and head_img_url == '': return False if nick_name != '': user.nick_name = filter_emoji(nick_name) if head_img_url != '': user.head_img_url = head_img_url return user.save()
def update_access_token(): url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format( settings.WECHAT_APP_ID, settings.WECHAT_APP_SECRET) try: resp = requests.get(url, verify=False, timeout=30) if resp.status_code != 200: log.error("访问状态码不正确: status_code = {}".format(resp.status_code)) return False json_data = json.loads(resp.text) access_token = json_data.get('access_token') expires_in = json_data.get('expires_in') if not isinstance(access_token, basestring) or not isinstance( expires_in, int): log.error("解析出来的数据类型不正确: {}".format(resp.text)) return False if expires_in <= 0: log.error("过期时间不正确: {}".format(expires_in)) return False log.info("成功获取token: access_token = {} expires_in = {}".format( access_token, expires_in)) # 设置redis cache_client.setex(WECHAT_ACCESS_TOKEN_KEY, expires_in, access_token) return True except Exception as e: log.error("访问token链接失败:") log.exception(e) return False
def delete_deploy_device_game(device_id): log.info("当前需要删除游戏的设备: device_id = {}".format(device_id)) # 找到游戏列表 game_list = GameListService.get_game_list() for game, version in game_list: is_success = DeviceGameService.delete(device_id, game) if not is_success: log.error("游戏删除失败: device_id = {} game = {}".format( device_id, game)) continue log.info("当前设备游戏删除成功: device_id = {} game = {}".format( device_id, game)) log.info("当前设备游戏删除完成: device_id = {}".format(device_id))
def get_device_game_state(): if not request.is_json: log.warn("参数错误...") return fail(HTTP_OK, u"need application/json!!") device_code = request.json.get('device_code') if not isinstance(device_code, basestring): return fail(HTTP_OK, u"参数类型错误!") update_state = DeviceService.get_update_state(device_code) if update_state is None: log.error("当前设备号没有获取到任何设备信息: {}".format(device_code)) return fail(HTTP_OK, u'当前设备号信息不正确,无法获取更新状态信息') return success(update_state)
def create(cls, name): role = cls(name=name) try: db.session.add(role) db.session.commit() except IntegrityError: log.error("主键重复: name = {}".format(name)) db.session.rollback() return None, False except Exception as e: log.error("未知插入错误: name = {}".format(name)) log.exception(e) return None, False return role, True
def get_user_by_id(user_id): # 先通过手机号码查找 user = UserService.get_user_by_mobile(user_id) if user is not None: return success(user.to_dict()) try: a_id = int(user_id) user = User.get(a_id) if user is not None: return success(user.to_dict()) except Exception as e: log.error("用户ID信息无法转换为 int 类型: user_id = {}".format(user_id)) log.exception(e) return success(None)