diff --git a/dcc/fetch.py b/dcc/fetch.py index d58dc1a..00121f5 100644 --- a/dcc/fetch.py +++ b/dcc/fetch.py @@ -5,32 +5,43 @@ import pathlib import urllib.request import zipfile + class Fetch(dcc.config.Base): - def get_parser(self, prog_name): - parser = super().get_parser(prog_name) - parser.add_argument("id_or_name") - return parser - - def take_action(self, parsed_args): - idgames_id = parsed_args.id_or_name - if not parsed_args.id_or_name.isdigit(): - idgames_id = self.search_idgames(parsed_args.id_or_name) + def get_parser(self, prog_name): + parser = super().get_parser(prog_name) + parser.add_argument("id_or_name") + return parser - with urllib.request.urlopen("https://www.doomworld.com/idgames/api/api.php?action=get&id={}&out=json".format(idgames_id)) as response: - reply = json.loads(response.read()) - rpath = "/".join([dcc.config.MIRROR, reply["content"]["dir"], reply["content"]["filename"]]) - wad = reply["content"]["filename"][0:-4] + def take_action(self, parsed_args): + idgames_id = parsed_args.id_or_name + if not parsed_args.id_or_name.isdigit(): + idgames_id = self.search_idgames(parsed_args.id_or_name) - with urllib.request.urlopen(rpath) as response: - z = zipfile.ZipFile(io.BytesIO(response.read())) - z.extractall(path=self.pwads.joinpath(wad)) + with urllib.request.urlopen( + "https://www.doomworld.com/idgames/api/" + + "api.php?action=get&id={}&out=json".format(idgames_id) + ) as response: + reply = json.loads(response.read()) + rpath = "/".join([ + dcc.config.MIRROR, + reply["content"]["dir"], + reply["content"]["filename"] + ]) + wad = reply["content"]["filename"][0:-4] - # TODO: explicit error handling. Let users choose when >1 result. - def search_idgames(self, wad): - with urllib.request.urlopen("https://www.doomworld.com/idgames/api/api.php?action=search&query={}&out=json".format(wad)) as response: - reply = json.loads(response.read()) - files = reply["content"]["file"] - if type(files) is dict: # One result. - return files["id"] - else: # More than one. Zero will raise an error. - return files[0]["id"] + with urllib.request.urlopen(rpath) as response: + z = zipfile.ZipFile(io.BytesIO(response.read())) + z.extractall(path=self.pwads.joinpath(wad)) + + # TODO: explicit error handling. Let users choose when >1 result. + def search_idgames(self, wad): + with urllib.request.urlopen( + "https://www.doomworld.com/idgames/api/" + + "api.php?action=search&query={}&out=json".format(wad) + ) as response: + reply = json.loads(response.read()) + files = reply["content"]["file"] + if type(files) is dict: # One result. + return files["id"] + else: # More than one. Zero will raise an error. + return files[0]["id"]