diff --git a/lokrez/__init__.py b/lokrez/__init__.py index 749ba2e..fc3b147 100644 --- a/lokrez/__init__.py +++ b/lokrez/__init__.py @@ -7,6 +7,7 @@ import logging import pathlib import requests import sys +import urllib import appdirs @@ -23,6 +24,135 @@ ROOTDIR = pathlib.Path(__file__).absolute().parent APPDIRS = appdirs.AppDirs(version.NAME, version.ENTITY) +LOG_DUMMY = logging.getLogger("dummy") +LOG_DUMMY.addHandler(logging.NullHandler()) + +DEFAULT_DIR_TEMPLATES = ROOTDIR / "templates" + +# ============================================================================= +def get_templates_list( + dir_templates = DEFAULT_DIR_TEMPLATES, + ): + + templates_list = [] + + dir_templates_path = pathlib.Path(dir_templates) + + for potential_template in dir_templates_path.iterdir(): + + if (potential_template / "template.svg.j2").is_file(): + templates_list.append(potential_template.name) + + return templates_list + +# ============================================================================= +def get_infos_from_url( + url, + token, + options = {}, + outform = "dict", + top = 8, + proxy = None, + log = LOG_DUMMY, + ): + + url_parsed = urllib.parse.urlparse(url) + + if url_parsed.netloc not in [ "smash.gg" ]: + raise ValueError("Unsupported domain name") + if outform not in [ "dict", "lkrz" ]: + raise ValueError("Unsupported outform") + + # ------------------------------------------------------------------------- + if url_parsed.netloc == "smash.gg": + + if (url_parsed.path.split("/")[1] != "tournament"): + raise Exception("No tournament found in url {}".format(url_parsed.path.split("/"))) + + # Get infos from smash.gg and write the config file + tournament, top_players = getTournamentTop( + id_or_slug = url_parsed.path.split("/")[2], + get_prefixes = options.get("use_smashgg_prefixes", False), + top = top, + token = token, + proxy = proxy, + log = log, + ) + + if tournament is None or top_players is None: + log.error("Could not load data from smash.gg") + raise Exception("Could not load data from smash.gg") + + # ------------------------------------------------------------------------- + if outform == "dict": + return { + "tournament": tournament, + "players": top_players, + } + + # ------------------------------------------------------------------------- + if outform == "lkrz": + return "\n".join( + [ tournament.conf() ] \ + + list(map( + lambda p:p.conf(), + top_players, + )) + ) + +# ============================================================================= +def generate_pic( + infos_or_lkrzfile = None, + template = None, + outform = "svg", + options = {}, + dir_templates = DEFAULT_DIR_TEMPLATES, + dir_res = None, + dir_cache = None, + log = LOG_DUMMY, + ): + + if outform not in ["svg", "png"]: + raise Exception("Unsupported outform") + + if type(infos_or_lkrzfile) == str: + # TODO : load lkrz as dict infos + raise NotImplementedError() + else: + infos = infos_or_lkrzfile + + # ------------------------------------------------------------------------- + # Build the context which will be passed to the template + context = { + "tournament": infos["tournament"].clean_name( + options.get( + "name_seo_delimiter", + None + ) + ), + "players" : sorted( + infos["players"], + key = lambda p: p.placement, + ), + "dir_res_ssbu": dir_res, + "dir_template": str(dir_templates/template), + "options": options.get("template_options", []), + } + + pic = export.generate_pic( + dir_templates, + template, + context, + outform, + log = log, + cachedir = dir_cache, + ) + + if pic is None: + raise Exception("Failed to generate pic") + + return pic + # ============================================================================= def main(): @@ -90,7 +220,7 @@ def main(): "--playerskinsdb", "-PD", type = (lambda s: s if s.startswith("http") else pathlib.Path(s)), default = ROOTDIR / "data" / "playerskinsdb.json", - help = "A JSON file path or urk matching player tags, characters,"\ + help = "A JSON file path or url matching player tags, characters,"\ " sponsors, and preferred skins", ) top8_parser.add_argument( @@ -102,7 +232,7 @@ def main(): top8_parser.add_argument( "--templatesdir", "-TD", type = pathlib.Path, - default = ROOTDIR / "templates", + default = DEFAULT_DIR_TEMPLATES, help = "The local result templates directory", ) @@ -211,10 +341,12 @@ def main(): log.debug("loading playerskins db from '{}'" \ .format(args.playerskinsdb)) try: - smashgg.PLAYERSKINS = requests.get(args.playerskinsdb).json() + PLAYERSKINS = requests.get(args.playerskinsdb).json() + smashgg.GET_PLAYERDATA = (lambda tag: PLAYERSKINS[tag.lower()]) except: with args.playerskinsdb.open("r", encoding="utf8") as f: - smashgg.PLAYERSKINS = json.load(f) + PLAYERSKINS = json.load(f) + smashgg.GET_PLAYERDATA = (lambda tag: PLAYERSKINS[tag.lower()]) # tournament = None @@ -283,7 +415,7 @@ def main(): [ tournament.conf() ] \ + list(map( lambda p:p.conf(), - top_players.values(), + top_players, )) ) @@ -310,7 +442,7 @@ def main(): context = { "tournament": tournament.clean_name(args.name_seo_delimiter), "players" : sorted( - top_players.values(), + top_players, key = lambda p: p.placement, ), "dir_res_ssbu": dir_res_ssbu, @@ -341,7 +473,7 @@ def getTournamentTop( top=8, token = "", proxy = None, - log=None): + log=LOG_DUMMY): """Returns a tuple : the smashgg.Tournament object and a list of the top smashgg.Player in that tournament.""" @@ -358,7 +490,7 @@ def getTournamentTop( # ------------------------------------------------------------------------- # Select the right event (the one with the most entrants or the most sets) - def selectBiggestEvent(data, log=None): + def selectBiggestEvent(data, log=LOG_DUMMY): try: event = data["events"][0] @@ -547,10 +679,14 @@ def getTournamentTop( # If some games or selections are null, this can happen continue - + # Sort top_players by rank instead of id: + top_players_sorted = sorted( + top_players.values(), + key = lambda p: p.placement, + ) # Return the data - return tournament, top_players + return tournament, top_players_sorted # ============================================================================= if __name__ == '__main__':