Commit Diff


commit - ecdd11bebb96abe6f21ba4c3e35dd4599e8bdac5
commit + b7194e0323fc165e03bd36a58ed584bd90811cfd
blob - aa6c67467a3f2a2cd9bdde4272237630f9ca26b5
blob + b0b625fa8b5632a71f3467cb1cf284af80831cde
--- lonk.py
+++ lonk.py
@@ -1,11 +1,9 @@
 #!/usr/bin/env python3
-import ssl
 from sqlite3 import connect as sqlite3_connect
-from argparse import ArgumentParser
 from json import loads as json_loads
 from pathlib import Path
-from socket import socket
-from urllib.parse import urlencode, urlunsplit, urljoin, urlsplit
+from sys import stdout
+from urllib.parse import urlencode, urlunsplit, urljoin, urlsplit, parse_qsl
 from urllib.request import urlopen
 from html.parser import HTMLParser
 
@@ -189,19 +187,28 @@ class HtmlToGmi(HTMLParser):
         return self.stack[0]
 
 
-def _format_honk(honk, header):
+def _format_honk(honk, header, lonk_url):
     assert honk["Noise"] == honk["HTML"], honk
     lines = [header, f'=> {honk["XID"]}', HtmlToGmi(_build_url()).feed(honk["HTML"])]
     for donk in (honk.get("Donks") or []):
+        gemini_url = urlunsplit(
+            (
+                "gemini",
+                lonk_url.netloc,
+                lonk_url.path + "/proxy",
+                urlencode({"m": donk["Media"], "u": donk["URL"]}),
+                ""
+            )
+        )
         lines.append(f'=> {donk["URL"]}')
-
+        lines.append(f'=> {gemini_url}')
         desc = donk.get("Desc") or donk.get("Name")
         if desc:
             lines.append(desc)
     return "\n".join(lines)
 
 
-def demo():
+def demo(lonk_url):
     collected = {}
 
     home = _load_from(action="gethonks", page="home")
@@ -236,13 +243,36 @@ def demo():
 
     for honk, header in reversed(collected.values()):
         print()
-        print(_format_honk(honk, header))
+        print(_format_honk(honk, header, lonk_url))
 
 
-def vgi():
-    print("20 text/gemini\r")
-    demo()
+def proxy(mime, url):
+    with urlopen(url, timeout=10) as f:
+        stdout.buffer.write(b"20 " + mime.encode() + b"\r\n")
+        stdout.buffer.write(f.read())
 
+
+def vgi(cert_hash):
+    url = urlsplit(input().strip())
+    page = [part for part in url.path.split("/") if part][-1]
+    if page == "lonk":
+        print("20 text/gemini\r")
+        demo(url)
+    elif page == "proxy":
+        query = {pair[0]: pair[1] for pair in parse_qsl(url.query)}
+        if "m" not in query or "u" not in query:
+            print("51 Not found\r")
+        else:
+            proxy(mime=query["m"], url=query["u"])
+    else:
+        print("51 Not found\r")
+
+
 if __name__ == '__main__':
-    # demo()
-    vgi()
+    from os import environ
+
+    cert_hash = environ.get("VGI_CERT_HASH")
+    if cert_hash:
+        vgi(cert_hash)
+    else:
+        print("60 Certificate required\r")