def attach(self): _attach = self._xml_json['attach'].split('/') if len(_attach) != 2: func.log_error('[gate] wechat_recharge_success attach is unvalid: {}'.format(_attach)) return None, None proxy_id, account_id = int(_attach[0]), int(_attach[1]) return proxy_id, account_id
def clear_unvalid_room(self): t = func.time_get() expire_t = t - 2 * 24 * 3600 # 玩家正常创建的房间保存2天 online_expire_t = t - 2 * 24 * 3600 # 在线匹配房间保存2天 delete_id_list = [] for room_id, room in self._rooms.iteritems(): if not room: delete_id_list.append(room_id) continue if room.is_online_match() and room.create_time <= online_expire_t: delete_id_list.append(room_id) elif room.create_time <= expire_t: delete_id_list.append(room_id) # 通知game节点删除 request_all_game_node('remove_unvalid_room', delete_id_list) # 本节点删除, 数据库删除 for room_id in delete_id_list: try: sql = 'delete from {} where room_id={}'.format(dbname.DB_ROOM, room_id) dbexecute.execute(sql) except Exception as e: func.log_error('[gate] RoomProxyManager clear_unvalid_room db room_id: {}, failed: {}'.format( room_id, e.message )) try: if room_id in self._rooms: del self._rooms[room_id] except Exception as e1: func.log_error('[gate] RoomProxyManager clear_unvalid_room cache room_id: {}, failed: {}'.format( room_id, e1.message ))
def room_voice_message(dynamic_id, voice_url): account_id = PlayerManager().query_account_id(dynamic_id) if not account_id: send.system_notice(dynamic_id, content.ENTER_DYNAMIC_LOGIN_EXPIRE) return room_manager = RoomManager() room_id = room_manager.query_player_room_id(account_id) if not room_id: send.system_notice(dynamic_id, content.ROOM_UN_ENTER) return room = room_manager.get_room(room_id) if not room: send.system_notice(dynamic_id, content.ROOM_UN_FIND) return player = room.get_player(account_id) if not player: func.log_error('[game] room_voice_message player is unvalid, account_id: {}, room_id: {}'.format( account_id, room_id)) send.system_notice(dynamic_id, content.ROOM_UN_ENTER) return t = func.time_get() if t - player.voice_message_t < 4: send.system_notice(dynamic_id, content.ROOM_CHAT_TO_FREQUENT) return player.voice_message_t = t send.voice_message_to_self(dynamic_id, voice_url) dynamic_id_list = room.get_room_dynamic_id_list() send.voice_message_to_all(dynamic_id_list, account_id, voice_url)
def backup_db(): today = datetime.date.today() backup_path = os.getcwd() + '/backup/' if not os.path.exists(backup_path): os.makedirs(backup_path) backup_file_name_tar = '{}{}_{}.tar.gz'.format(backup_path, constant.DB_NAME, today) if os.path.isfile(backup_file_name_tar): func.log_info('[gate] backup_db file: {} is exist'.format(backup_file_name_tar)) return backup_file_name = '{}{}_{}.sql'.format(backup_path, constant.DB_NAME, today) try: cmd = 'mysqldump -h{} -u{} -p{} {} --default_character-set={} > {}'.format( constant.DB_HOST, constant.DB_USER, constant.DB_PASSWD, constant.DB_NAME, 'utf8', backup_file_name) os.system(cmd) # tar tar = tarfile.open(backup_file_name_tar, 'w:gz') for root, _, files in os.walk(backup_path): for f in files: if 'sql' not in f: continue full_path = os.path.join(root, f) tar.add(full_path, arcname=f) tar.close() except Exception as e: func.log_error('[gate] backup_db failed: {}'.format(e.message)) finally: os.system('rm -rf {}'.format(backup_file_name))
def bind_proxy(dynamic_id, proxy_id): if not proxy_id: send.system_notice(dynamic_id, content.PROXY_ID_LACK) return sql = 'select account_id from {} where account_id = {}'.format(dbname.DB_ACCOUNT, proxy_id) if not dbexecute.query_one(sql): send.system_notice(dynamic_id, content.PROXY_ID_ERROR) return user = UserManager().get_user_by_dynamic(dynamic_id) if not user: send.system_notice(dynamic_id, content.ENTER_DYNAMIC_LOGIN_EXPIRE) return if user.proxy_id > 0: send.system_notice(dynamic_id, content.PROXY_ID_EXIST) return if user.account_id == proxy_id: send.system_notice(dynamic_id, content.PROXY_ID_ERROR) # PROXY_ID_SELF return user.proxy_id = proxy_id try: proxy_stastics(proxy_id) except Exception as e: func.log_error('[gate] bind_proxy proxy_id: {}, failed: {}'.format(proxy_id, e.message)) change.award_gold(user, constant.GOLD_BIND_PROXY, origins.ORIGIN_PROXY_ACTIVE) # save user.user_save() send.bind_success(dynamic_id, proxy_id) send.system_notice(dynamic_id, content.PROXY_ID_SUCCESS) func.log_info('[gate] bind_proxy account_id: {} bind proxy_id: {}'.format(user.account_id, proxy_id))
def notice_user_channel_login_verify(account_id, verify_key, address, **kwargs): func.log_info('[user channel verify] account_id: {} \t verify_key: {}, address: {}'.format( account_id, verify_key, address)) UserManager().record_verify_key(account_id, verify_key, address) user = UserManager().get_user(account_id) if user: user.sync_information(**kwargs) else: try: change_info = dict() if kwargs.get('name'): change_info['name'] = kwargs.get('name') if kwargs.get('sex'): change_info['sex'] = kwargs.get('sex') if kwargs.get('head_frame'): change_info['head_frame'] = kwargs.get('head_frame') if kwargs.get('head_icon'): change_info['head_icon'] = kwargs.get('head_icon') if change_info: dbexecute.update_record( table=dbname.DB_ACCOUNT, where={'account_id': account_id}, data=change_info ) except Exception as e: func.log_error('[gate] notice_user_channel_login_verify account_id: {}, failed: {}'.format( account_id, e.message)) return None
def heart_tick(dynamic_id): user = UserManager().get_user_by_dynamic(dynamic_id) if not user: func.log_error('[gate] dynamic_id: {} not find'.format(dynamic_id)) return UserManager().heart_tick(user.account_id) send.send_heart_tick(dynamic_id)
def load_special_infomation(self, info_id): sql = 'select * from {} where id={}'.format(dbname.DB_INFORMATION, info_id) result = dbexecute.query_one(sql) if result: self._parse_infomation(result) else: func.log_error('[config] load_special_infomation unfind info_id: {} in db'.format(info_id))
def account_register(dynamic_id, address, user_name, password): if not user_name or not password: send.system_notice(dynamic_id, content.ACCOUNT_NULL) return if not func.check_english(user_name): send.system_notice(dynamic_id, content.ACCOUNT_ENGLISH) return sql = 'select * from {} where user_name="{}"'.format( dbname.DB_ACCOUNT, user_name) if dbexecute.query_one(sql): send.system_notice(dynamic_id, content.ACCOUNT_EXIST) return uuid = user_name sex = func.random_get(1, 2) name = user_name head_frame = '' head_icon = '' account_id = _register_process(user_name, password, name, uuid, '', channel.CHANNEL_ZERO, sex, head_frame, head_icon) if account_id: func.log_info( '[Auth] user_name: {}, account_id: {}, address: {} register success' .format(user_name, account_id, address)) send.account_register(dynamic_id, user_name, password, account_id) else: func.log_error( '[Auth] user_name: {} register failed'.format(user_name))
def render(self, request): try: account_id = int(request.args.get('id')[0]) login.proxy_stastics(account_id) except Exception as e: func.log_error('[gate] RechargeStasticsTest error: {}'.format(e.message)) return "SUCCESS"
def do_data_received(self, target_key, request): if client_service.is_target_local(target_key): result = client_service.callTarget(target_key, request) return target_key, result else: func.log_error('[ClientFactory] target_key: {} can not find in client_service'.format(target_key)) return None, None
def clear_files(paths): valid_days = 7 c_t = time.gmtime() c_st = time.strftime('%Y-%m-%d', c_t) c_year, c_month, c_day = c_st.split('-') c_td = datetime.datetime(int(c_year), int(c_month), int(c_day)) if not os.path.exists(paths): return file_list = os.listdir(paths) for f in file_list: t = time.gmtime(os.stat('{}/{}'.format(paths, f))[stat.ST_CTIME]) # file create time st = time.strftime('%Y-%m-%d', t) year, month, day = st.split('-') td = datetime.datetime(int(year), int(month), int(day)) days = (c_td - td).days if days >= valid_days: f_path = '{}/{}'.format(paths, f) try: if f_path.strip() == '/': continue os.remove(f_path) except Exception as e: func.log_error('[gate] clear_logs f_path: {}, failed: {}'.format(f_path, e.message))
def stop(self): if self._timer: try: self._timer.cancel() except Exception as e: func.log_error('[game] ITimer stop failed, error: {}'.format(e.message)) finally: self._timer = None
def deferred_error_handle(e): """ 延迟对象的错误处理 :param e: :return: """ func.log_error(str(e)) return
def check_repeated_order_from_db(pay): order_id = pay.order_id sql = 'select id from {} where op_id={}'.format(dbname.DB_RECHARGE, order_id) if dbexecute.query_one(sql): func.log_error('[gate] check_repeated_order_from_db order_id: {} repeated'.format(order_id)) return True else: return False
def forwarding(target_key, dynamic_id, address, data): if auth_service.is_target_local(target_key): return auth_service.callTarget(target_key, dynamic_id, address, data) else: func.log_error( 'target_key: {} do not exist in auth'.format(target_key), func.__function_pos__()) return None
def stop(self): if self._timer: try: self._timer.cancel() except Exception as e: func.log_error('[game] ITimer stop failed, error: {}'.format( e.message)) finally: self._timer = None
def drop_user(self, user): if user: user.user_save() user.disconnect() try: del self._users[user.account_id] del self._users_dynamic[user.dynamic_id] except Exception as e: func.log_error('{}'.format(e.message), func.__function_pos__())
def remove_rooms(self, room_id_list): for room_id in room_id_list: try: if room_id in self._rooms: del self._rooms[room_id] except Exception as e: func.log_error('[game] remove_rooms room_id: {}, failed: {}'.format( room_id, e.message ))
def attach(self): _attach = self._xml_json['attach'].split('/') if len(_attach) != 2: func.log_error( '[gate] wechat_recharge_success attach is unvalid: {}'.format( _attach)) return None, None proxy_id, account_id = int(_attach[0]), int(_attach[1]) return proxy_id, account_id
def verify(self): self._xml_json.pop('sign') self.get_sign(self._xml_json) func.log_info('[gate] pre_sign: {}'.format(self._sign)) func.log_info('[gate] cur_sign: {}'.format(self._xml_json['sign'])) if self._sign != self._xml_json['sign']: func.log_error('[gate] WechatResponse xml_sign: {} != sgin: {}'.format( self._xml_json['sign'], self._sign)) return False return True
def load_special_infomation(self, info_id): sql = 'select * from {} where id={}'.format(dbname.DB_INFORMATION, info_id) result = dbexecute.query_one(sql) if result: self._parse_infomation(result) else: func.log_error( '[config] load_special_infomation unfind info_id: {} in db'. format(info_id))
def verify(self): self._xml_json.pop('sign') self.get_sign(self._xml_json) func.log_info('[gate] pre_sign: {}'.format(self._sign)) func.log_info('[gate] cur_sign: {}'.format(self._xml_json['sign'])) if self._sign != self._xml_json['sign']: func.log_error( '[gate] WechatResponse xml_sign: {} != sgin: {}'.format( self._xml_json['sign'], self._sign)) return False return True
def do_when_stop(): func.log_info('[game] ---------------------------> node do_when_stop begin') for room_id, room in RoomManager().rooms.items(): try: if not room: continue room.room_save() except Exception as e: func.log_error('[game] room save room_id: {}, error: {} room_data: {}'.format( room_id, e.message, room.get_save_data() )) func.log_info('[game] node do_when_stop end <-----------------------')
def do_when_stop(): func.log_info('[gate] ---------------------------> node do_when_stop begin') for account_id, user in UserManager().get_all_users().items(): try: if not user: continue user.user_save() except Exception as e: func.log_error('[gate] user save account_id: {}, error: {}, user_data: {}'.format( account_id, e.message, user.get_save_data() )) func.log_info('[gate] node do_when_stop end <-----------------------')
def do(self): interval = 30 * 60 self.start(interval) func.log_info('[gate] SaveTimer check do, next: {}'.format(interval)) all_users = UserManager().get_all_users() for account_id, user in all_users.iteritems(): try: user.user_save() except Exception as e: func.log_error( '[gate] SaveTimer account_id: {}, failed: {}'.format( account_id, e.message))
def drop_room(self, room): room_id = room.room_id for account_id in room.room_account_id_list: if account_id in self._player_room and self._player_room[account_id] == room_id: del self._player_room[account_id] try: if room_id in self._rooms: del self._rooms[room_id] except Exception as e: func.log_error('[game] drop_room room_id: {}, failed: {}'.format( room_id, e.message ))
def gm_award_gold(account_id, gold_count): if account_id != 0: change.award_gold_by_account(account_id, gold_count, origins.ORIGIN_RECHARGE_GM) return 'account_id: {}, add gold: {} SUCCESS'.format(account_id, gold_count) else: try: gm_award_gold_all(gold_count) return 'add all user gold: {} SUCCESS'.format(gold_count) except Exception as e: func.log_error('[gate] gm_award_gold award all gold_count: {}, failed: {}'.format( gold_count, e.message )) return 'failed.'
def _check_weixin_token(openid, token): url = "https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s" % ( token, openid) ret = urllib.urlopen(url).read() ret_json_obj = json.loads(ret) if ret_json_obj['errcode'] == 0: return True else: func.log_error( "_check_weixin_token fail openid: {} token: {} ret: {}".format( openid, token, ret)) return False pass
def do_when_stop(): func.log_info( '[gate] ---------------------------> node do_when_stop begin') for account_id, user in UserManager().get_all_users().items(): try: if not user: continue user.user_save() except Exception as e: func.log_error( '[gate] user save account_id: {}, error: {}, user_data: {}'. format(account_id, e.message, user.get_save_data())) func.log_info('[gate] node do_when_stop end <-----------------------')
def do_when_stop(): func.log_info( '[game] ---------------------------> node do_when_stop begin') for room_id, room in RoomManager().rooms.items(): try: if not room: continue room.room_save() except Exception as e: func.log_error( '[game] room save room_id: {}, error: {} room_data: {}'.format( room_id, e.message, room.get_save_data())) func.log_info('[game] node do_when_stop end <-----------------------')
def log_gold(account_id, count, remain, origin_id): t = func.time_get() insert_data = { 'account_id': account_id, 'count': count, 'remain': remain, 'origin_id': origin_id, 'time': t } result = dbexecute.insert_record(**{'table': dbname.DB_LOG_GOLD, 'data': insert_data}) if not result: func.log_error('[gate] log_gold account_id: {}, count: {}, remain: {}, origin_id: {}, time: {}'.format( account_id, count, remain, origin_id, t ))
def wechat_recharge_success(notice_content): if not notice_content: return func.log_info('[gate] wechat_recharge_success content:\n {}'.format(notice_content)) pay = recharge_wechat.WechatResponse(notice_content) func.log_info('[gate] wechat_recharge_success pay.xml_json:\n {}'.format(pay.xml_json)) xml_json = pay.xml_json proxy_id, account_id = pay.attach if not proxy_id or not account_id: return user = UserManager().get_user(account_id) if not user: func.log_error('[gate] wechat_recharge_success account_id: {} un exist'.format(account_id)) return pay.init( nonce_str=xml_json['nonce_str'], attach=xml_json['attach'], order_id=xml_json['out_trade_no'], total_fee=xml_json['total_fee'], spbill_create_ip='' # IP不参与签名 ) if check_repeated_order_from_db(pay): func.log_error('[gate] wechat_recharge_success repeated order notice account_id: {}, proxy_id: {}'.format( account_id, proxy_id )) return money = pay.money if pay.verify(): recharge_gold = calc_money_to_gold(money) save_order_to_db(pay, recharge_gold, origins.ORIGIN_RECHARGE_WECHAT) change.award_gold(user, recharge_gold, origins.ORIGIN_RECHARGE_MONEY) # statistic statistic_money = int(money / 100) # fee to yuan recharge_statistic_self(user, statistic_money) recharge_statistic_proxy(user.proxy_id, statistic_money) # save user.user_save() func.log_info('[gate] wechat_recharge_success account_id: {}, money: {} SUCCESS'.format( account_id, money )) else: func.log_info('[gate] wechat_recharge_success account_id: {}, money: {} FAILED'.format( account_id, money ))
def award_gold_by_account(account_id, count, origin): if count < 0: return user = UserManager().get_user(account_id) if user: award_gold(user, count, origin) else: try: sql = 'update {} set gold = gold + {} where account_id = {}'.format( dbname.DB_ACCOUNT, int(count), account_id) dbexecute.execute(sql) func.log_info('[gate] award_gold_by_account account_id: {}, add gold: {}, origin: {} offline'.format( account_id, count, origin )) except Exception as e: func.log_error('[gate] award_gold_by_account account_id: {}, count: {}, origin: {}, failed: {}'.format( account_id, count, origin, e.message ))
def add_play_history(account_id_list, history_data): user_manager = UserManager() room_type = history_data['room_type'] room_help = history_data['room_help'] all_change_point = history_data['all_change_point'] # {account_id: last_change_point, ...} all_change_gold = history_data['all_change_gold'] for account_id in account_id_list: user = user_manager.get_user(account_id) if not user: func.log_error('[gate] add_play_history account_id: {} lost history data'.format(account_id)) return change_point = all_change_point.get(account_id, 0) sync_game_point(user, room_type, change_point) if room_help == games.HELP_ONLINE_MATCH: gold_point = all_change_gold.get(account_id, 0) sync_game_gold_point(user, gold_point) user.add_play_history(history_data) func.log_info('[gate] account_id: {} get play history'.format(account_id))
def _for_each_field_props(props): """ 遍历字段列表生成sql语句 :param props: :return: """ sql = '' if props == '*': return '*' elif isinstance(props, list): for prop in props: sql = sql + prop + ',' sql = sql[:-1] return sql else: func.log_error( '[each_query_props] props {} must be list'.format(props)) return sql
def user_back_front(dynamic_id, operate): account_id = PlayerManager().query_account_id(dynamic_id) if not account_id: send.system_notice(dynamic_id, content.ENTER_DYNAMIC_LOGIN_EXPIRE) return False room_manager = RoomManager() room_id = room_manager.query_player_room_id(account_id) if not room_id: send.system_notice(dynamic_id, content.ROOM_UN_ENTER) return False room = room_manager.get_room(room_id) if not room: send.system_notice(dynamic_id, content.ROOM_UN_FIND) return False player = room.get_player(account_id) if not player: func.log_error('[game] user_back_front ROOM_UN_ENTER, account_id: {}, room_id: {}'.format( account_id, room_id)) send.system_notice(dynamic_id, content.ROOM_UN_ENTER) return player.status_ex = status.PLAYER_STATUS_BACK if operate == operators.USER_OPERATOR_BACK else status.PLAYER_STATUS_FRONT notice_all_room_user_operator(room, account_id, operate) return True
def render(self, request): try: recharge.wechat_recharge_success(request.content.read()) except Exception as e: func.log_error('[gate] RechargeWechatNotify error: {}'.format(e.message)) return "SUCCESS"
def forwarding(target_key, dynamic_id, address, data): if auth_service.is_target_local(target_key): return auth_service.callTarget(target_key, dynamic_id, address, data) else: func.log_error('target_key: {} do not exist in auth'.format(target_key), func.__function_pos__()) return None
def connect_to_game(self, ip, port): if ip and port: self._connect(ip, port) else: func.log_error('[Client] connect_to_game ip and port can not be null')
def system_notice_9001(request): argument = system_pb2.m_9001_toc() argument.ParseFromString(request) func.log_error('[SYSTEM] {}'.format(argument.content)) return None