From 1aba6365aa5c7feade50c0b185206b8029a4938e Mon Sep 17 00:00:00 2001 From: Matt Singleton Date: Mon, 7 Sep 2020 16:18:18 -0500 Subject: move redirect logic into gemini module --- gemini.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) (limited to 'gemini.py') diff --git a/gemini.py b/gemini.py index 58f3358..beb2d5c 100644 --- a/gemini.py +++ b/gemini.py @@ -78,7 +78,19 @@ def urljoin(base: str, url: str) -> str: url = re.sub('^gemini:', 'http:', url) return re.sub('^http:', 'gemini:', urllib.parse.urljoin(base, url)) -def get(url: str) -> dict: +def get(url: str, follow_redirects: bool = True) -> dict: + response = _get(url) + if follow_redirects is True: + count = 0 + while response['status'][0] == '3': + count += 1 + if count > 20: + raise Exception('Redirect loop') + print('redirect: {}'.format(response['meta'])) + response = _get(response['meta']) + return response + +def _get(url: str) -> dict: url_parts = urllib.parse.urlsplit(url) if len(url_parts.path) == 0: return { @@ -97,7 +109,7 @@ def get(url: str) -> dict: port = 1965 if url_parts.port is None else url_parts.port with socket.create_connection((url_parts.hostname, port)) as sock: with context.wrap_socket(sock, server_hostname=url_parts.hostname) as ssock: - ssock.sendall('gemini://{}{}\r\n'.format(url_parts.hostname, url_parts.path).encode('utf8')) + ssock.sendall('{url}\r\n'.format(url=url).encode('utf8')) fp = ssock.makefile(mode='rb') header = fp.readline(1027) status, meta = header.decode('utf8').split(None, 1) -- cgit v1.2.3