Commit Diff


commit - f49711de655a1b1a8b980f04f84a143e48a1f4a8
commit + 577b12da144a505da89ff3710bedb70d3e67175e
blob - 580d1bf327e876a177985a50f460893e61b91c8a
blob + da97511c010f4a47ae6bd8b745a3e771351d49ed
--- lonk.py
+++ lonk.py
@@ -4,8 +4,9 @@ from mimetypes import guess_type
 from os import environ
 from pathlib import Path
 from sys import stdout
+from sqlite3 import connect as sqlite3_connect
 from urllib.error import HTTPError, URLError
-from urllib.parse import urlencode, urlunsplit, urljoin, urlsplit, parse_qsl
+from urllib.parse import urlencode, urlunsplit, urljoin, urlsplit, parse_qsl, unquote
 from urllib.request import urlopen
 from html.parser import HTMLParser
 
@@ -258,8 +259,52 @@ def demo(lonk_url):
     for honk, header in reversed(collected.values()):
         print()
         print(_format_honk(honk, header, fn_media_url))
+
+
+def _create_schema(db_con):
+    db_con.execute("""
+        CREATE TABLE
+            client (
+                client_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                cert_hash TEXT UNIQUE,
+                honk_url TEXT NOT NULL,
+                token TEXT NOT NULL
+            )"""
+    )
+
+
+def db_connect():
+    db_file_path = Path(__file__).parent / ".local" / "db"
+    db_file_path.parent.mkdir(parents=True, exist_ok=True)
+    db_exist = db_file_path.exists()
+    db_con = sqlite3_connect(db_file_path)
+    if not db_exist:
+        _create_schema(db_con)
+    return db_con
+
+
+def lonk(cert_hash, lonk_url):
+    db_con = db_connect()
+    row = db_con.execute("SELECT client_id, honk_url, token FROM client WHERE cert_hash = ?", (cert_hash, )).fetchone()
+    if not row:
+        new_client_url = urlunsplit(
+            ("gemini", lonk_url.netloc, lonk_url.path + "/new_client", "", "")
+        )
+        print(f"30 {new_client_url}\r")
+        return
+    raise RuntimeError(row)
 
 
+def new_client(cert_hash, lonk_url):
+    db_con = db_connect()
+    if not lonk_url.query:
+        print(f"10 Honk server URL (for example: https://honk.any-key.press)\r")
+        return
+    splitted = urlsplit(unquote(lonk_url.query))
+    honk_url = urlunsplit((splitted.scheme, splitted.netloc, "", "", ""))
+    raise RuntimeError(honk_url)
+
+
 def proxy(mime, url):
     with urlopen(url, timeout=10) as f:
         stdout.buffer.write(b"20 " + mime.encode() + b"\r\n")
@@ -274,7 +319,10 @@ def vgi(cert_hash):
     url = urlsplit(input().strip())
     page = [part for part in url.path.split("/") if part][-1]
     if page == "lonk":
-        demo(url)
+        # demo(url)
+        lonk(cert_hash, url)
+    elif page == "new_client":
+        new_client(cert_hash, 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: