#!/usr/bin/python3
import asyncio, traceback, socket, ssl
from urllib.parse import urlparse
from flask import Flask, request, redirect
from hypercorn.config import Config
from hypercorn.asyncio import serve
app = Flask(__name__)
@app.route("/")
def root():
return """
Gem2Browser
Gem2Browser
"""
@app.route("/gem")
def relay():
url = request.args.get('gemini')
if url == None:
return redirect("/")
code = "Something went wrong... \n"
title = "Something went wrong..."
try:
gsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
fulladdr = "gemini://" + url
gemsocket = ssl._create_unverified_context().wrap_socket(gsocket, server_hostname=urlparse(fulladdr).hostname)
print(fulladdr)
print(urlparse(fulladdr).hostname)
gemsocket.connect((urlparse(fulladdr).hostname, 1965))
gemsocket.send(bytes("gemini://" + url + "\r\n", "UTF-8"))
received = ""
while True:
gemresponse = gemsocket.recv(2048)
print(gemresponse)
if gemresponse.decode() != "":
received += gemresponse.decode()
else:
break
print(received)
received = received.replace("\r", "")
firstline = True
redirected = False
gemtext = True
code = ""
for i in received.split("\n"):
if firstline:
if i.split(" ")[0][0] == "3":
return redirect("/gem?gemini=" + i.split(" ")[1][9:])
elif i.split(" ")[0][0] != "2":
return f'\nSomething went wrong... Something went wrong... The specified Gemini server returned a status of: {i}
'
else:
firstline = False
if i.split(" ")[1] != "text/gemini":
return f'\nSomething went wrong... Something went wrong... This path returned a file that isn\'t Gemtext, which Gem2Browser doesn\'t support downloading files.
'
else:
if i[0:1] == "# ":
if title == "Something went wrong...":
title = i[2:]
temp = i[2:]
code += f"{temp} \n"
elif i[0:2] == "## ":
temp = i[3:]
code += f"{temp} \n"
elif i[0:3] == "### ":
temp = i[4:]
code += f"{temp} \n"
elif i[0:1] == "* ":
temp = i[2:]
code += f""
else:
code += f"{code}
\n"
print(i)
if title == "Something went wrong...":
title = "gemini://" + url
except:
code += traceback.format_exc()
return f'\n{title} {code}'
# Run the Hypercorn ASGI server
conf = Config()
conf.bind = "0.0.0.0:2009"
asyncio.run(serve(app, conf))