Follow redirects.

This commit is contained in:
Solderpunk 2019-06-24 18:04:10 +03:00
parent fbc5a19238
commit e948ce0a13
1 changed files with 34 additions and 22 deletions

View File

@ -8,6 +8,15 @@ import urllib.parse
menu = [] menu = []
hist = [] hist = []
def absolutise_url(base, relative):
# Absolutise relative links
if "://" not in relative:
# Python's URL tools somehow only work with known schemes?
base = base.replace("gemini://","http://")
relative = urllib.parse.urljoin(base, relative)
relative = relative.replace("http://", "gemini://")
return relative
while True: while True:
# Get input # Get input
cmd = input("> ").strip() cmd = input("> ").strip()
@ -30,22 +39,30 @@ while True:
if parsed_url.scheme != "gemini": if parsed_url.scheme != "gemini":
print("Sorry, Gemini links only.") print("Sorry, Gemini links only.")
continue continue
# Do the Gemini transaction # Do the Gemini transaction, following redirects
try: while True:
s = socket.create_connection((parsed_url.netloc, 1965)) try:
context = ssl.SSLContext() s = socket.create_connection((parsed_url.netloc, 1965))
context.check_hostname = False context = ssl.SSLContext()
context.verify_mode = ssl.CERT_NONE context.check_hostname = False
s = context.wrap_socket(s, server_hostname = parsed_url.netloc) context.verify_mode = ssl.CERT_NONE
s.sendall((parsed_url.path + '\r\n').encode("UTF-8")) s = context.wrap_socket(s, server_hostname = parsed_url.netloc)
except: s.sendall((parsed_url.path + '\r\n').encode("UTF-8"))
print("Network error!") except:
continue print("Network error!")
# Check header and fail if not okay continue
fp = s.makefile("rb") # Get header and check for redirects
header = fp.readline() fp = s.makefile("rb")
header = header.decode("UTF-8").strip() header = fp.readline()
status, mime = header.split("\t") header = header.decode("UTF-8").strip()
status, mime = header.split("\t")
# If this isn't a redirect, we're done
if not status.startswith("3"):
break
# Follow the redirect
url = absolutise_url(url, mime)
parsed_url = urllib.parse.urlparse(url)
# Fail if transaction was not successful
if not status.startswith("2"): if not status.startswith("2"):
print("Error %s: %s" % (status, mime)) print("Error %s: %s" % (status, mime))
continue continue
@ -63,12 +80,7 @@ while True:
for line in body.splitlines(): for line in body.splitlines():
if line.startswith("\t") and line.count("\t") == 2: if line.startswith("\t") and line.count("\t") == 2:
_, text, link_url = line.split("\t") _, text, link_url = line.split("\t")
# Absolutise relative links link_url = absolutise_url(url, link_url)
if "://" not in link_url:
# Python's URL tools somehow only work with known schemes?
base = url.replace("gemini://","http://")
link_url = urllib.parse.urljoin(base, link_url)
link_url = link_url.replace("http://", "gemini://")
menu.append(link_url) menu.append(link_url)
print("[%d] %s" % (len(menu), text)) print("[%d] %s" % (len(menu), text))
else: else: