def get(self, map, country): Logger.log(f"RankingApi - GET - map: {map}, country: {country}") map = str(map) country = str(country) scores, error = DatabaseHandler.get_scores(map, country) if error == 0: results = [] for score in scores: results.append(score.export_to_dict()) return Response(json.dumps(results), mimetype="application/json", status=200) elif error == 1: return Response(json.dumps({"error": "Map does not exists"}), mimetype="application/json", status=404) elif error == 2: return Response(json.dumps({"error": "Country does not exists"}), mimetype="application/json", status=404) else: return Response(json.dumps({"error": "Generic error"}), mimetype="application/json", status=400)
def __list_select_callback(self, event): Logger.log("List clicked.") selection = event.widget.curselection() if selection: index = selection[0] text = str(event.widget.get(index)) map_name = text[:text.find("|") - 1] Logger.log(f"Map selected: '{map_name}'") self.__open_map_details(map_name)
def get(self, id): Logger.log(f"MapIdApi - GET - id: {id}") map = DatabaseHandler.get_map(str(id)) if map == None: return Response(json.dumps({"error": "Not found"}), mimetype="application/json", status=404) else: return Response(json.dumps(map.export_to_dict()), mimetype="application/json", status=200)
def get(self): Logger.log("MapApi - GET") maps = DatabaseHandler.get_all_maps() result = [] for map in maps: temp = map.export_to_dict() temp.pop("data") result.append(temp) return Response(json.dumps(result), mimetype="application/json", status=200)
def save_data_to_file(self) -> bool: Logger.log( f"Saving data of '{self.__table_name}' table to '{self.__file_path}'." ) data_to_save = "" for data in self.__data_rows: data_to_save += DatabaseTable.__DATA_SEPARATOR.join( str(x) for x in data.export_to_save()) data_to_save += "\n" return FileHandler.write_to_file(self.__file_path, data_to_save)
def load_data_from_file(self) -> bool: self.__data_rows = [] Logger.log( f"Loading data for '{self.__table_name}' table from '{self.__file_path}'." ) if os.path.exists(self.__file_path): lines = FileHandler.read_from_file(self.__file_path) if (lines != None): for line in lines: if len(line) > 0: try: self.__data_rows.append( self.__accept_type.create_from_array( line.rstrip("\n").split( DatabaseTable.__DATA_SEPARATOR))) except AssertionError: Logger.log("Data corruption", True) return False else: Logger.log(f"File {self.__file_path} load failed.") return False Logger.log( f"Loading data for '{self.__table_name}' table from '{self.__file_path}' has ended." ) return True
def __login(self): Logger.log("Trying to Login...") payload = { "username": self.__user.get(), "password": self.__pass.get() } Logger.log("Making POST request...") r = None try: r = requests.post(url=Config.get_connection_string() + "/api/auth/login", json=payload) except requests.exceptions.RequestException: messagebox.showerror("Connection error", "Failed to connect with to server") return Logger.log(f"Recieved response: {r.status_code}") if r.status_code == 200: data = r.json() Logger.log("Login successful") self.token = data["token"] self.username = payload["username"] self.__exit() else: messagebox.showerror("Login error", "Invalid email or password")
def get(self, user): Logger.log(f"ScoreUserApi - GET - user: {user}") user = str(user) scores = DatabaseHandler.get_user_scores(user) if scores == None: return Response(json.dumps({"error": "User not found"}), mimetype="application/json", status=404) results = [] for map in scores: results.append(map.export_to_dict()) return Response(json.dumps(results), mimetype="application/json", status=200)
def delete(self, id): Logger.log(f"MapIdApi - DELETE - id: {id}") user_id = get_jwt_identity() user = DatabaseHandler.get_user_username(user_id) if user in None: return Response(None, status=403) map: MapData = DatabaseHandler.get_map(str(id)) if map.user != user.username: return Response(None, status=403) if DatabaseHandler.remove_map(str(id)): return Response(json.dumps({"id": str(id)}), mimetype="application/json", status=200) else: return Response(json.dumps({"error": "Not found"}), mimetype="application/json", status=404)
def mulAcToken(isHost, limit=''): print(time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time()))) logger = Logger('AccessToken') account = MySqlDao() # res = account.rows("select * from nikeaccount where id >50 and id <= 100") if limit != '': res = account.rows("select * from nikeaccount limit " + limit) else: res = account.rows("select * from nikeaccount") print("[nkBot]>get " + str(len(res)) + " accounts Access Token") data = [] for re in res: if re[4] and re[8]: data.append((re[0], re[4], re[8], isHost)) if len(data): pool = ThreadPoolExecutor() res = list(pool.map(accessToken, data)) logger.write(res) else: pass
def __init__(self) -> None: Logger.log("Initializing database...") self.__good = False if not os.path.exists(Database.__DATABASE_DIR): Logger.log("Creating database directory.") try: os.makedirs(Database.__DATABASE_DIR) except: Logger.log("Unable to create a data directory.", True) self.__tables: Dict[str, DatabaseTable] = {} self.__good = True Logger.log("Database initialized.")
def post(self): Logger.log("ScoreApi - POST") user_id = get_jwt_identity() user = DatabaseHandler.get_user_username(user_id) if user is None: return Response(None, mimetype="application/json", status=403) body = request.get_json() Logger.log(body) if "map_id" in body and "score" in body: map_id = str(body["map_id"]) score = 0 try: score = int(body["score"]) except ValueError: return Response(json.dumps( {"error": "Score must be an integer"}), mimetype="application/json", status=400) result = DatabaseHandler.add_score(user.username, map_id, score) if result == 0: return Response(None, status=204) else: if result == 1: return Response(json.dumps( {"error": "Map does not exists"}), mimetype="application/json", status=404) elif result == 2: return Response(json.dumps( {"error": "Score must be a positive number"}), mimetype="application/json", status=400) else: return Response(json.dumps({"error": "Generic error"}), mimetype="application/json", status=400) else: return Response(None, status=400)
def __register(self): Logger.log("Trying to Register...") payload = { "email": self.__email.get(), "username": self.__user.get(), "password": self.__pass.get(), "country": self.__country.get() } Logger.log("Making POST request...") r = None try: r = requests.post(url=Config.get_connection_string() + "/api/auth/sign", json=payload) except requests.exceptions.RequestException: messagebox.showerror("Connection error", "Failed to connect with to server", parent=self.__root) self.__exit() return Logger.log(f"Recieved response: {r.status_code}") if r.status_code == 204: messagebox.showinfo("Register info", "Successfully registered!", parent=self.__root) self.__exit() else: data = r.json() messagebox.showerror("Register error", data["error"], parent=self.__root)
def add_row(self, data) -> bool: Logger.log(f"Adding '{str(data)}' to '{self.__table_name}' table.") if not isinstance(data, self.__accept_type): Logger.log( f"Incorrect data type. Was '{str(type(data))}', but '{str(self.__accept_type)}' was expected." ) return False for temp in self.__data_rows: if data == temp: Logger.log( f"There is already object '{str(data)}' in the table.") return False self.__data_rows.append(data) if not self.save_data_to_file(): Logger.log(f"'{self.__table_name}' table save failed.", True) return False Logger.log(f"Data added successfuly to table '{self.__table_name}'") return True
def post(self): Logger.log("MapApi - POST") user_id = get_jwt_identity() user = DatabaseHandler.get_user_username(user_id) if user is None: return Response(None, mimetype="application/json", status=403) body = request.get_json() Logger.log(body) if "map_name" in body and "data" in body: map_name = str(body["map_name"]) data = str(body["data"]) if len(map_name) < 1: return Response(json.dumps( {"error": "Map_name cannot be empty"}), mimetype="application/json", status=400) if len(data) < 1: return Response(json.dumps({"error": "Data cannot be empty"}), mimetype="application/json", status=400) id = DatabaseHandler.add_map(map_name, data, user.username) if id == None: return Response(json.dumps( {"error": "Map with given name already exists"}), mimetype="application/json", status=400) else: return Response(json.dumps({"id": id}), mimetype="application/json", status=200) else: return Response(json.dumps({"error": "Generic error"}), mimetype="application/json", status=400)
def add_table(self, table_name, data_type: type) -> bool: Logger.log(f"Adding table: {table_name}") if table_name in self.__tables: Logger.log( f"There is already a table named '{table_name}' in database.") return False database_table = DatabaseTable(table_name, data_type, Database.__DATABASE_DIR) if not database_table.is_good(): Logger.log(f"Table initialization failed: {table_name}") return False self.__tables[table_name] = database_table Logger.log(f"Table added: {table_name}") return True
def start_game(user: str, map_name: str, map_data: str, highscore: int) -> int: print(user, map_data, highscore) if Config.GAME_EXECUT_COMMAND == "": return -6 if not FileHandler.write_to_file( Config.GAME_CONFIG_PATH, f"{user}\n{map_name}\n{map_data}\n{highscore}\n"): return -2 process = subprocess.Popen(Config.GAME_EXECUT_COMMAND, shell=True) process.wait() if process.returncode == 0: Logger.log("Game ended successfully. Exit code: 0") lines = FileHandler.read_from_file(Config.GAME_RESULT_PATH) if lines == None or lines == []: return -3 if os.path.exists(Config.GAME_CONFIG_PATH): os.remove(Config.GAME_CONFIG_PATH) if os.path.exists(Config.GAME_RESULT_PATH): os.remove(Config.GAME_RESULT_PATH) try: result = int(lines[0]) if result < 0: return -5 return result except ValueError: return -4 else: Logger.log(f"Game ended with exit code {process.returncode}.") return -1
def remove_row(self, data) -> bool: Logger.log(f"Removing '{str(data)}' from '{self.__table_name}' table.") if not isinstance(data, self.__accept_type): Logger.log( f"Incorrect data type. Was '{str(type(data))}', but '{str(self.__accept_type)}' was expected.", True) found = False for row in self._data_rows: if row == data: self._data_rows.remove(row) found = True if found: if not self.save_data_to_file(): Logger.log(f"'{self.__table_name}' table save failed.", True) return False Logger.log( f"Data removed successfuly from table '{self.__table_name}'.") else: Logger.log(f"Data not found in table '{self.__table_name}'.") return False return found
def remove_rows(self, predicat: Callable[[Any], bool]) -> bool: flag = False for data in list(filter(predicat, self.__data_rows)): flag = True Logger.log( f"Removed '{str(data)}'' from table '{self.__table_name}'.") self.__data_rows.remove(data) if flag: if not self.save_data_to_file(): Logger.log(f"'{self.__table_name}' table save failed.", True) return False Logger.log( f"Data removed successfuly from table '{self.__table_name}'.") else: Logger.log(f"No data found in table '{self.__table_name}'.") return True
def __init__(self, table_name: str, data_type: type, db_dir: str) -> None: Logger.log(f"Initializing table {table_name}...") self.__good = False self.__accept_type = data_type self.__table_name = table_name self.__data_rows = [] self.__file_path = f"{db_dir}/{self.__table_name}{DatabaseTable.__DATABASE_TABLE_FILE_EXTENSION}" self.__good = self.load_data_from_file() if self.__good: Logger.log(f"Table {table_name} initialized.") else: Logger.log(f"Table {table_name} falied to initialize.")
from flask.app import Flask from flask_restful import Api from flask_bcrypt import Bcrypt from flask_jwt_extended import JWTManager from Database.Database import Database from Map.MapData import MapData from Score.Score import Score from Server.DatabaseHandler import DatabaseHandler from Server.Routes import initialize_routes from Tools.Logger import Logger from Tools.Settings import Config from User.User import User Config.load_config_file() Logger.initialize() if __name__ == "__main__": if os.path.exists("./.env"): os.environ['ENV_FILE_LOCATION'] = "./.env" else: Logger.log("Env file not present", True) app = Flask(__name__) app.config.from_envvar('ENV_FILE_LOCATION') api = Api(app) bcrypt = Bcrypt(app) jwt = JWTManager(app) database = Database() if not database.is_good():
def find_rows(self, predicat: Callable[[Any], bool]): if not self.load_data_from_file(): Logger.log(f"'{self.__table_name}' table save failed.", True) return None return list(filter(predicat, self.__data_rows))
def get(self): Logger.log("CountriesApi - GET") return Countries.get_list(), 200
def __register(self): Logger.log("Opening RegisterWindow") RegisterWindow(self.__root)
from Tools.Logger import Logger from Environment.BanditEnvironment_stationary import BanditEnvironment import numpy as np env = BanditEnvironment(5, 5) logger = Logger(5, env) res = np.array(logger.log_per_client_mean_best_buy) rew_mean = np.array(logger.log_per_client_reward_mean) print(res) print(rew_mean) logger.add_reward_client(1, 1, None) res = np.array(logger.log_per_client_mean_best_buy) rew_mean = np.array(logger.log_per_client_reward_mean) print(res) print(rew_mean) logger.add_reward_client(1, 1, None) res = np.array(logger.log_per_client_mean_best_buy) rew_mean = np.array(logger.log_per_client_reward_mean) print(res) print(rew_mean)
def get_table(self, table_name: str) -> DatabaseTable: if table_name in self.__tables: return self.__tables[table_name] else: Logger.log(f"There is no DatabaseTable with name '{table_name}'") return None
def __play_map(self): r = None try: r = requests.get(url = Config.get_connection_string() + f"/api/score/user/{self.__username}") except requests.exceptions.RequestException: messagebox.showerror("Connection error", "Failed to connect with to server", parent = self.__root) self.__root.destroy() return scores: List = r.json() my_score = None for score in scores: if score["map_id"] == self.__map_data["map_id"]: my_score = score points = 0 if my_score != None: points = my_score["points"] new_points = GameManager.start_game(self.__username, self.__map_data["map_name"], self.__map_data["data"], points) if new_points == -1: messagebox.showerror("Error", "Game crashed!", parent = self.__root) return elif new_points == -2: messagebox.showerror("Error", "Couldn't create game config file!", parent = self.__root) return elif new_points == -3: messagebox.showerror("Error", "Couldn't read game result file!", parent = self.__root) return elif new_points == -4: messagebox.showerror("Error", "Result file does not contain an integer!", parent = self.__root) return elif new_points == -5: messagebox.showerror("Error", "Result is less then 0!", parent = self.__root) return elif new_points == -6: messagebox.showerror("Error", "Game does not exists!", parent = self.__root) return if new_points > points: r = requests.post(url = Config.get_connection_string() + "/api/score", headers = {"Authorization": "Bearer " + self.__token}, json = {"map_id": self.__map_data["map_id"], "score": new_points}) if r.status_code != 204: messagebox.showerror("Error", r.json()["error"], parent = self.__root) else: Logger.log("New score saved.") messagebox.showinfo("Success", "New score saved!", parent = self.__root) try: r = requests.get(url = Config.get_connection_string() + f"/api/ranking/{self.__map_data['map_id']}:{self.__country.get()}") scores: List = r.json() sorted_scores = sorted(scores, key = lambda x: x["points"], reverse = True) self.__fill_list(sorted_scores) except requests.exceptions.RequestException: messagebox.showerror("Connection error", "Failed to connect with to server", parent = self.__root) self.__root.destroy() return else: Logger.log("Old score remains.") messagebox.showinfo("Success", "Old score remains...", parent = self.__root)