From 81249ca89c193c9977531f73db43f13c98665deb Mon Sep 17 00:00:00 2001 From: swee Date: Sun, 12 Jan 2025 22:31:01 -0800 Subject: [PATCH] Update server.py --- server.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/server.py b/server.py index 92af663..876d763 100644 --- a/server.py +++ b/server.py @@ -1,5 +1,5 @@ #!/usr/bin/python3 -import asyncio, traceback +import asyncio, traceback, socket, ssl from flask import Flask, request, redirect from hypercorn.config import Config from hypercorn.asyncio import serve @@ -33,7 +33,51 @@ def relay(): code = "

Something went wrong...

\n" title = "Something went wrong..." try: - raise Exception("Not implemented") + gsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + gemsocket = ssl.wrap_socket(gsocket) + gemsocket.connect((url, 1965)) + gemsocket.send(bytes("gemini://" + url + "\r\n", "UTF-8")) + received = "" + while True: + gemresponse = gemsocket.recv(2048) + if gemresponse: + received += gemresponse.decode() + else: + break + 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]) + 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" + if title == "Something went wrong...": + title = "gemini://" + url except: code += traceback.format_exc() return f'\n{title}{code}'