def get(self): """ Returns user's publicity. """ current_user_username = get_jwt_identity() user_status = DbHandler.get_user_publicity( DbHandler.get_user_id(current_user_username)) return make_response(jsonify(publicity=user_status), 200)
def post(self, id): """ Return links related to specific user ID, if user is public. Also if you provide special date, it will return links from that time. """ args = parser.parse_args() date_from = args['date_from'] page = args['page'] page_size = args['page_size'] if page and page_size: if page_size > MAX_LINKS_PER_PAGE: return make_response( jsonify(msg="Requested page size " + "is larger than our max limit!"), 400) links_list = DbHandler.get_public_user_links( id, page, page_size, date_from) else: links_list = DbHandler.get_public_user_links(id, date_from=date_from) if links_list == 'USER_NOT_FOUND': return make_response(jsonify(msg='User not found!'), 404) elif links_list == 'LINK_NOT_FOUND': return make_response(jsonify(msg='Link not found!'), 404) elif links_list == 'USER_NOT_PUBLIC': return make_response(jsonify(msg='User is not public!'), 403) elif links_list == 'WRONG_DATE_FORMAT': return make_response( jsonify(msg='Input date does not match format' + '"YYYY-MM-DD hh:mm"'), 400) else: return make_response(jsonify(links_list), 200)
def post(self): """ Return users activities paginated from a special date (If provided). """ args = parser.parse_args(strict=True) date_from = args['date_from'] page = args['page'] page_size = args['page_size'] if page and page_size: if page_size > MAX_ACTIVITIES_PER_PAGE: return make_response( jsonify(msg="Requested page size " + "is larger than our max limit!"), 400) activity_list = DbHandler.get_users_activity_list( page, page_size, date_from) else: activity_list = DbHandler.get_users_activity_list( date_from=date_from) if activity_list == 'WRONG_FORMAT': return make_response( jsonify(msg="Input does not match format 'YYYY-MM-DD hh:mm'"), 400) elif activity_list == 'NOT_FOUND': return make_response( jsonify(msg="Didn't found any activity from that time"), 404) else: return make_response(jsonify(activity_list), 200)
def get(self, pattern): """ Return links that contains special keyword paginated. """ current_user_username = get_jwt_identity() args = parser.parse_args() page = args['page'] page_size = args['page_size'] if page and page_size: if page_size > MAX_LINKS_PER_PAGE: return make_response( jsonify(msg="Requested page size " + "is larger than our max limit!"), 400 ) links_list = DbHandler.get_links_by_pattern(current_user_username, pattern, page, page_size) else: links_list = DbHandler.get_links_by_pattern(current_user_username, pattern) if links_list == 'PATTERN_NOT_FOUND': return make_response( jsonify(msg="Pattern not found!"), 404 ) else: return make_response( jsonify(links_list), 200 )
def __init__(self): self.data = None self.db_handler = None self.error_log = [] self.start_time = datetime.now() self.current_time = datetime.now() self.players = [] self.db_handler = DbHandler()
def delete(self): """ Delete current user's profile """ current_user_username = get_jwt_identity() status = DbHandler.delete_user_profile(current_user_username) if status == 'OK': return make_response(jsonify(msg="User's profile deleted."), 200) else: return make_response(jsonify(msg="Server Error!"), 500)
def get(self, id=None): """ If client requests for /categories will get whole categories; else if requests for /categories/[ID] will get specified category. """ current_user_username = get_jwt_identity() categories_list = DbHandler.get_categories(current_user_username, id) if categories_list == 'ID_NOT_FOUND': return make_response(jsonify(msg="Category not found!"), 404) else: return make_response(jsonify(categories_list), 200)
def get(self, id): """ Return links by special Category ID paginated""" args = parser.parse_args() current_user_username = get_jwt_identity() page = args['page'] page_size = args['page_size'] if page and page_size: if page_size > MAX_LINKS_PER_PAGE: return make_response( jsonify(msg="Requested page size " + "is larger than our max limit!"), 400) links_list = DbHandler.get_links_by_category( current_user_username, id, page, page_size) else: links_list = DbHandler.get_links_by_category( current_user_username, id) if links_list == 'CATEGORY_NOT_FOUND': return make_response(jsonify(msg="Category not found!"), 404) else: return make_response(jsonify(links_list), 200)
def put(self, id): """ Update categories related to Link ID. """ current_user_username = get_jwt_identity() args = parser.parse_args() new_categories = args['new_categories'] update_status = DbHandler.update_link_categories( current_user_username, new_categories, id) if update_status == 'LINK_NOT_FOUND': return make_response(jsonify(msg="Link ID not found!"), 404) else: return make_response(jsonify(msg="Categories updated."), 200)
def __init__(self): self.dbHandler = DbHandler() self.data = self.dbHandler.data self.key = [ "RACE", "JOB", "EV", "EVMAX", "EA", "EAMAX", "COU", "INT", "CHA", "AD", "FO", "AT", "PRD", "DESTINY", "SKILLS", "GOLD", "SILVER", "BRONZE", "LEVEL", "SEX", "XP", "NAME", "STUFF", "WEAPONS", "PLAYER" ] self.mapping = { self.key[0]: "Race", self.key[1]: "Métier", self.key[2]: "Energie vitale", self.key[3]: "Energie vitale maximale", self.key[4]: "Energie astrale", self.key[5]: "Energie astrale maximale", self.key[6]: "Courage", self.key[7]: "Intelligence", self.key[8]: "Charisme", self.key[9]: "Adresse", self.key[10]: "Force", self.key[11]: "Attaque", self.key[12]: "Parade", self.key[13]: "Points de destin", self.key[14]: "Compétences", self.key[15]: "Pièces d'or", self.key[16]: "Pièces d'argent", self.key[17]: "Pièces de bronze", self.key[18]: "Niveau", self.key[19]: "Sexe", self.key[20]: "Points d'expérience", self.key[21]: "Nom", self.key[22]: "Equipement", self.key[23]: "Armes", self.key[23]: "Joueur" }
def put(self): """ Update user's publicity setting. """ parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('publicity', type=bool, required=True) args = parser.parse_args() current_user_username = get_jwt_identity() publicity = args['publicity'] status = DbHandler.update_user_publicity(current_user_username, publicity) if status == 'OK': return make_response(jsonify(msg="Publicity updated."), 200) else: return make_response(jsonify(msg="Server Error!"), 500)
def reset_password(reset_token: str, new_password: str) -> str: """ Step 3: Change user's password if the token for changing password is valid""" try: user_id = ResetPasswordCore.__validate_reset_password_token( reset_token) except SignatureExpired: return ('EXPIRED') except BadSignature: return ('INVALID_TOKEN') status = DbHandler.reset_user_forgotten_password(user_id, new_password) if status == 'OK': return ('OK') else: return ('FAILED')
def get_n_digit_auth_code(username: str) -> str: """ Step 1: Start process of resetting password. Return hash format of user's ID + random generated N digit code.""" id = DbHandler.get_user_id(username) if id == -1: return "USER_NOT_FOUND" random_code = ResetPasswordCore.__generate_n_digit_code() forget_password_rendered_page = ResetPasswordCore.\ __render_forget_password_page(random_code) ResetPasswordCore.__send_email_to_user( username, 'Restfulness Forget Password Code', forget_password_rendered_page) return (ResetPasswordCore.__generate_hash_string(id, random_code))
def delete(self, id): current_user_username = get_jwt_identity() remove_status = DbHandler.remove_link(current_user_username, id) if remove_status == "OK": return make_response( jsonify(msg="Link removed successfully.", link_id=id), 200 ) elif remove_status == "USER_IS_NOT_OWNER": return make_response( jsonify(msg="You don't have permission to " + "remove this link"), 403 ) elif remove_status == "ID_NOT_FOUND": return make_response( jsonify(msg="Link doesn't exists!"), 404 )
def post(self): args = parser.parse_args() username = args["username"] password = args["password"] # Check if username and password are correct user = DbHandler.validate_login(username, password) return_message = "" if user: # Identity can be any data that is json serializable access_token = create_access_token(identity=username) return_message = make_response(jsonify(access_token=access_token), 200) else: return_message = make_response( jsonify({"msg": "Bad username or password"}), 401) return return_message
def post(self): parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('url', type=str, required=True) # Get a list of strings {'categories': ['X', 'Y', 'Z']} parser.add_argument('categories', type=str, action='append') args = parser.parse_args() current_user_username = get_jwt_identity() url = args['url'] categories_name = args['categories'] # Validate link if not validators.url(url): return make_response( jsonify(msg="Link is not valid. Valid link looks like: " + "http://example.com or https://example.com"), 400) link_id = DbHandler.append_new_link(current_user_username, url, categories_name) return make_response(jsonify(id=link_id), 200)
def post(self): args = parser.parse_args() username = args["username"] password = args["password"] # Validate if username is Email or not if not validators.email(username): return make_response( jsonify(msg="Username should be an valid Email."), 400) validate_sign_up = DbHandler.add_new_user(username, password) return_message = "" if validate_sign_up == "OK": return_message = make_response( jsonify(username=username, msg="User created"), 200) elif validate_sign_up == "USER_EXISTS": return_message = make_response(jsonify({"msg": "Username exists"}), 403) return return_message
class CharacterDBHandler: def __init__(self): self.dbHandler = DbHandler() self.data = self.dbHandler.data self.key = [ "RACE", "JOB", "EV", "EVMAX", "EA", "EAMAX", "COU", "INT", "CHA", "AD", "FO", "AT", "PRD", "DESTINY", "SKILLS", "GOLD", "SILVER", "BRONZE", "LEVEL", "SEX", "XP", "NAME", "STUFF", "WEAPONS", "PLAYER" ] self.mapping = { self.key[0]: "Race", self.key[1]: "Métier", self.key[2]: "Energie vitale", self.key[3]: "Energie vitale maximale", self.key[4]: "Energie astrale", self.key[5]: "Energie astrale maximale", self.key[6]: "Courage", self.key[7]: "Intelligence", self.key[8]: "Charisme", self.key[9]: "Adresse", self.key[10]: "Force", self.key[11]: "Attaque", self.key[12]: "Parade", self.key[13]: "Points de destin", self.key[14]: "Compétences", self.key[15]: "Pièces d'or", self.key[16]: "Pièces d'argent", self.key[17]: "Pièces de bronze", self.key[18]: "Niveau", self.key[19]: "Sexe", self.key[20]: "Points d'expérience", self.key[21]: "Nom", self.key[22]: "Equipement", self.key[23]: "Armes", self.key[23]: "Joueur" } def initialize(self): self.dbHandler.retrieve_game() def mappingCharStat(self, aKey, aChar): if aKey == self.key[0]: return aChar.race elif aKey == self.key[1]: return aChar.job elif aKey == self.key[2]: return aChar.ev elif aKey == self.key[3]: return aChar.evMax elif aKey == self.key[4]: return aChar.ea elif aKey == self.key[5]: return aChar.eaMax elif aKey == self.key[6]: return aChar.courage elif aKey == self.key[7]: return aChar.intelligence elif aKey == self.key[8]: return aChar.charisme elif aKey == self.key[9]: return aChar.adresse elif aKey == self.key[10]: return aChar.force elif aKey == self.key[11]: return aChar.attaque elif aKey == self.key[12]: return aChar.parade elif aKey == self.key[13]: return aChar.pointsDeDestin elif aKey == self.key[14]: return str(aChar.competences) elif aKey == self.key[15]: return aChar.piecesOr elif aKey == self.key[16]: return aChar.piecesArgent elif aKey == self.key[17]: return aChar.piecesBronze elif aKey == self.key[18]: return aChar.niveau elif aKey == self.key[19]: return aChar.sexe elif aKey == self.key[20]: return aChar.experience elif aKey == self.key[21]: return aChar.name elif aKey == self.key[22]: return str(aChar.stuff) elif aKey == self.key[23]: return str(aChar.weapons) elif aKey == self.key[24]: return str(aChar.userName) def readFileForCharacter(self, userId): for aPlayer in self.data['settings']['characters']: if aPlayer["PLAYER"] == userId: return aPlayer def importCharacter(self, userName): values = self.readFileForCharacter(userName) aNewCharacter = CharacterV2() aNewCharacter.userName = values["PLAYER"] aNewCharacter.name = values["NAME"] aNewCharacter.name = values["NAME"] aNewCharacter.race = values["RACE"] aNewCharacter.job = values["JOB"] aNewCharacter.ev = values["EV"] aNewCharacter.evMax = values["EVMAX"] aNewCharacter.ea = values["EA"] aNewCharacter.eaMax = values["EAMAX"] aNewCharacter.courage = values["COU"] aNewCharacter.intelligence = values["INT"] aNewCharacter.charisme = values["CHA"] aNewCharacter.adresse = values["AD"] aNewCharacter.force = values["FO"] aNewCharacter.attaque = values["AT"] aNewCharacter.parade = values["PRD"] aNewCharacter.pointsDeDestin = values["DESTINY"] aNewCharacter.competences = values["SKILLS"] aNewCharacter.piecesOr = values["GOLD"] aNewCharacter.piecesArgent = values["SILVER"] aNewCharacter.piecesBronze = values["BRONZE"] aNewCharacter.niveau = values["LEVEL"] aNewCharacter.sexe = values["SEX"] aNewCharacter.experience = values["XP"] aNewCharacter.stuff = values["STUFF"] aNewCharacter.weapons = values["WEAPONS"] return aNewCharacter def convertKey(self, aKey): return self.mapping[aKey] def displayBasicInfos(self, aCharacter): return self.displayListOfInfos(0x00ff00, aCharacter, ["RACE", "JOB", "SEX", "LEVEL", "XP"], aCharacter.name) def displayBasicStats(self, aCharacter, displayName=False): return self.displayListOfInfos( 0x00ff00, aCharacter, ["EV", "EA", "DESTINY", "GOLD", "AT", "PRD", "AD"], (aCharacter.name if displayName else None)) def displayAttackInfo(self, aCharacter, displayName=False): return self.displayListOfInfos( 0x00ff00, aCharacter, ["AT", "PRD", "AD"], (aCharacter.name if displayName else None)) def displayMoneyInfos(self, aCharacter, displayName=False): return self.displayListOfInfos( 0x00ff00, aCharacter, ["GOLD"], (aCharacter.name if displayName else None)) def displaySkills(self, aCharacter, displayName=False): return self.displayListOfInfos( 0x00ff00, aCharacter, ["SKILLS"], (aCharacter.name if displayName else None)) def displayStuff(self, aCharacter, displayName=False): return self.displayListOfInfos( 0x00ff00, aCharacter, ["STUFF"], (aCharacter.name if displayName else None)) def displayWeapons(self, aCharacter, displayName=False): return self.displayListOfInfos( 0x00ff00, aCharacter, ["WEAPONS"], (aCharacter.name if displayName else None)) def displayListOfInfos(self, color, aCharacter, listOfStats, title=None): embedFormated = discord.Embed(color=color, title=title) for aStat in listOfStats: strValue = self.mappingCharStat(aStat, aCharacter) if (aStat == "EA" or aStat == "EV"): strValue = (self.mappingCharStat(aStat, aCharacter) + "/" + self.mappingCharStat(aStat + "MAX", aCharacter)) elif aStat == "GOLD": strValue = (self.mappingCharStat("GOLD", aCharacter) + "/" + self.mappingCharStat("SILVER", aCharacter) + "/" + self.mappingCharStat("BRONZE", aCharacter)) embedFormated.add_field(name=self.mapping[aStat], value=strValue, inline=True) return embedFormated def displayMinimumInfoCharacter(self, aCharacter): embeds = [self.displayBasicStats(aCharacter, True)] return embeds def displayWeaponsCharacter(self, aCharacter): embeds = [self.displayWeapons(aCharacter, True)] return embeds def displayStuffCharacter(self, aCharacter): embeds = [self.displayStuff(aCharacter, True)] return embeds def displaySkillsCharacter(self, aCharacter): embeds = [self.displaySkills(aCharacter, True)] return embeds def displayInfoCharacter(self, aCharacter): embeds = [ self.displayListOfInfos( 0x00ff00, aCharacter, ["RACE", "JOB", "SEX", "GOLD", "LEVEL", "XP"]), self.displayListOfInfos(0x00ff00, aCharacter, ["EV", "EA", "DESTINY"]), self.displayListOfInfos(0x00ff00, aCharacter, ["AT", "PRD", "AD"]), self.displayListOfInfos(0x00ff00, aCharacter, ["SKILLS", "STUFF", "WEAPONS"]) ] return embeds def moneyOperation(self, userName, amount): theChar = self.readFileForCharacter(userName) print(theChar) operations = amount.split("/") if len(operations) >= 1: tempOr = int(theChar["GOLD"]) + int(operations[0]) if (tempOr < 0): tempOr = 0 theChar["GOLD"] = str(tempOr) if len(operations) >= 2: tempArgent = int(theChar["SILVER"]) + int(operations[1]) if (tempArgent < 0): tempArgent = 0 theChar["SILVER"] = str(tempArgent) if len(operations) >= 3: tempBronze = int(theChar["BRONZE"]) + int(operations[2]) if (tempBronze < 0): tempBronze = 0 theChar["BRONZE"] = str(tempBronze) self.dbHandler.update_game() return theChar["GOLD"], theChar["SILVER"], theChar["BRONZE"] def increaseEv(self, userName, amount): theCharSheet = self.readFileForCharacter(userName) tempEv = int(theCharSheet["EV"]) + amount if (tempEv > int(theCharSheet["EVMAX"])): tempEv = int(theCharSheet["EVMAX"]) if (tempEv < 0): tempEv = 0 theCharSheet["EV"] = str(tempEv) self.dbHandler.update_game() return theCharSheet["EV"] def decreaseEv(self, userName, amount): return self.increaseEv(userName, (0 - amount)) def increaseEvGroup(self, amount): print("increase") result = [] for aPlayer in self.dbHandler.data['settings']['characters']: print("Decrease player" + aPlayer["PLAYER"]) tempEv = int(aPlayer["EV"]) + amount if (tempEv > int(aPlayer["EVMAX"])): tempEv = int(aPlayer["EVMAX"]) if (tempEv < 0): tempEv = 0 aPlayer["EV"] = str(tempEv) result.append({ 'id': aPlayer["PLAYER"], 'remainingLife': aPlayer["EV"] }) print('Save Changes') self.dbHandler.update_game() return result def decreaseEvGroup(self, amount): print("Decrease") return self.increaseEvGroup((0 - amount))
class SettingsHandler: pattern = "%d/%m/%Y - %H:%M" key_start_time = "start_time" key_current_time = "current_time" key_players = "players" key_settings = 'settings' def __init__(self): self.data = None self.db_handler = None self.error_log = [] self.start_time = datetime.now() self.current_time = datetime.now() self.players = [] self.db_handler = DbHandler() def initialize(self): self.db_handler.retrieve_game() self.data = self.db_handler.data self.fill_data() def fill_data(self): # TODO Improve way of handling non-present date self.start_time = datetime.strptime(self.data[self.key_settings][self.key_start_time], self.pattern) self.current_time = datetime.strptime(self.data[self.key_settings][self.key_current_time], self.pattern) self.players = self.data[self.key_settings][self.key_players] def get_elapsed_time(self): return self.current_time - self.start_time def add_time(self, delta): a_time_delta = timedelta(minutes=delta) self.current_time += a_time_delta return self.current_time def save_settings(self): self.data[self.key_settings][self.key_current_time] = self.current_time.strftime(self.pattern) self.db_handler.update_game() #TODO Improve result handling # 'normal','bon','excellent' def compute_rest(self, quality, delta): if delta > 540: delta = 540 if quality == "normal": return int(delta / 240) elif quality == "bon": return int(delta / 120) elif quality == "excellent": return int(delta / 60) else: self.error_log.append({"error_code": 3, "error_msg": "Invalid Rest Quality", "context": "compute_rest", "timestamp": datetime.now()}) raise ValueError("Choix entre 'normal'|'bon'|'excellent'") # 'normale','rapide','barbare' def compute_walk(self, rythme, delta): injury = 0 if delta > 480: injury += int(1+(delta-480)/60) if rythme == "normale": injury += 0 elif rythme == "rapide": injury += int(delta / 240) + 1 elif rythme == "barbare": injury += int(delta / 120) + 1 else: self.error_log.append({"error_code": 4, "error_msg": "Invalid Walk Quality", "context": "compute_walk", "timestamp": datetime.now()}) raise ValueError("Choix entre 'normale'|'rapide'|'barbare'") return injury def handle_rest(self, quality, length, embed): db_handler = self.get_character_db_handler() try: delta = int(length) except ValueError: print("Not an integer") return False try: heal = self.compute_rest(quality, delta) except ValueError as e: embed.add_field(value=str(e)) return False players = db_handler.increaseEvGroup(heal) for a_player in players: embed.add_field( name= "Soin enregistrée", value="Le joueur <@" + a_player['id'] + "> a soigné " + str(int(heal)) + " points de vie.\nIl reste " + a_player['remainingLife'] + " points de vie.", inline=False) return True def handle_walk(self, rythme, length, embed): db_handler = self.get_character_db_handler() delta = 0 try: delta = int(length) except ValueError: print("Not an integer") return False injury = 0 try: injury = self.compute_walk(rythme, delta) except ValueError as e: embed.add_field(value=str(e)) return False players = db_handler.decreaseEvGroup(injury) for a_player in players: embed.add_field( name= "Blessure enregistrée", value="Le joueur <@" + a_player['id'] + "> a pris " + str(int(injury)) + " points de dégats.\nIl reste " + a_player['remainingLife'] + " points de vie.", inline=False) return True def get_character_db_handler(self): db_handler = CharacterDBHandler() return db_handler