gemini-demo-1/gemini-demo.py

117 lines
3.8 KiB
Python
Raw Permalink Normal View History

2019-06-24 14:47:59 +00:00
#!/usr/bin/env python3
import cgi
import mailcap
import os
2019-06-24 14:47:59 +00:00
import socket
import ssl
import tempfile
2020-02-03 20:38:18 +00:00
import textwrap
2019-06-24 14:47:59 +00:00
import urllib.parse
caps = mailcap.getcaps()
2019-06-24 14:47:59 +00:00
menu = []
hist = []
2019-06-24 15:04:10 +00:00
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
2019-06-24 14:47:59 +00:00
while True:
# Get input
cmd = input("> ").strip()
# Handle things other than requests
if cmd.lower() == "q":
print("Bye!")
break
# Get URL, from menu, history or direct entry
if cmd.isnumeric():
url = menu[int(cmd)-1]
elif cmd.lower() == "b":
# Yes, twice
url = hist.pop()
url = hist.pop()
else:
url = cmd
if not "://" in url:
url = "gemini://" + url
parsed_url = urllib.parse.urlparse(url)
if parsed_url.scheme != "gemini":
print("Sorry, Gemini links only.")
continue
2019-08-19 18:09:19 +00:00
# Do the Gemini transaction
try:
while True:
2019-06-24 15:04:10 +00:00
s = socket.create_connection((parsed_url.netloc, 1965))
context = ssl.SSLContext()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
s = context.wrap_socket(s, server_hostname = parsed_url.netloc)
2019-08-11 19:27:40 +00:00
s.sendall((url + '\r\n').encode("UTF-8"))
# Get header and check for redirects
fp = s.makefile("rb")
header = fp.readline()
header = header.decode("UTF-8").strip()
2020-02-03 20:38:18 +00:00
status, mime = header.split()
2019-08-19 18:09:19 +00:00
# Handle input requests
if status.startswith("1"):
# Prompt
query = input("INPUT" + mime + "> ")
url += "?" + urllib.parse.quote(query) # Bit lazy...
# Follow redirects
elif status.startswith("3"):
url = absolutise_url(url, mime)
parsed_url = urllib.parse.urlparse(url)
# Otherwise, we're done.
else:
break
except Exception as err:
print(err)
continue
2019-06-24 15:04:10 +00:00
# Fail if transaction was not successful
2019-06-24 14:47:59 +00:00
if not status.startswith("2"):
print("Error %s: %s" % (status, mime))
continue
# Handle text
if mime.startswith("text/"):
# Decode according to declared charset
2019-06-24 14:47:59 +00:00
mime, mime_opts = cgi.parse_header(mime)
body = fp.read()
body = body.decode(mime_opts.get("charset","UTF-8"))
# Handle a Gemini map
if mime == "text/gemini":
menu = []
2020-03-07 19:24:26 +00:00
preformatted = False
for line in body.splitlines():
2020-03-07 19:24:26 +00:00
if line.startswith("```"):
preformatted = not preformatted
elif preformatted:
print(line)
elif line.startswith("=>") and line[2:].strip():
2019-07-21 21:10:41 +00:00
bits = line[2:].strip().split(maxsplit=1)
link_url = bits[0]
link_url = absolutise_url(url, link_url)
menu.append(link_url)
2019-07-21 21:10:41 +00:00
text = bits[1] if len(bits) == 2 else link_url
print("[%d] %s" % (len(menu), text))
else:
2020-02-03 20:38:18 +00:00
print(textwrap.fill(line, 80))
# Handle any other plain text
else:
print(body)
# Handle non-text
2019-06-24 14:47:59 +00:00
else:
tmpfp = tempfile.NamedTemporaryFile("wb", delete=False)
tmpfp.write(fp.read())
tmpfp.close()
cmd_str, _ = mailcap.findmatch(caps, mime, filename=tmpfp.name)
os.system(cmd_str)
os.unlink(tmpfp.name)
# Update history
2019-06-24 14:47:59 +00:00
hist.append(url)