1 ecdd11be 2024-09-11 continue #!/usr/bin/env python3
2 1719b036 2024-09-03 continue from json import loads as json_loads
3 29500f51 2024-09-20 continue from mimetypes import guess_type
4 d76a52db 2024-09-17 continue from os import environ
5 1719b036 2024-09-03 continue from pathlib import Path
6 4acbf994 2024-09-25 continue from sys import stdout, stderr
7 577b12da 2024-09-24 continue from sqlite3 import connect as sqlite3_connect
8 4acbf994 2024-09-25 continue from time import clock_gettime, CLOCK_MONOTONIC
9 15efabff 2024-09-13 continue from urllib.error import HTTPError, URLError
10 e03b8dd3 2024-09-25 continue from urllib.parse import urlencode, urlunsplit, urljoin, urlsplit, parse_qsl, unquote, quote
11 1719b036 2024-09-03 continue from urllib.request import urlopen
12 a7cabe95 2024-09-04 continue from html.parser import HTMLParser
15 a7cabe95 2024-09-04 continue class _BaseTag:
16 a7cabe95 2024-09-04 continue def __init__(self, tag, attrs):
17 a7cabe95 2024-09-04 continue self.tag = tag
19 a7cabe95 2024-09-04 continue def on_data(self, data):
20 e03b8dd3 2024-09-25 continue raise AssertionError("The method must be overridden")
22 a7cabe95 2024-09-04 continue def flush(self):
23 e03b8dd3 2024-09-25 continue raise AssertionError("The method must be overridden")
26 a7cabe95 2024-09-04 continue class ParagraphTag(_BaseTag):
27 a7cabe95 2024-09-04 continue def __init__(self, tag, attrs):
28 a7cabe95 2024-09-04 continue super().__init__(tag, attrs)
29 a7cabe95 2024-09-04 continue self.content = []
30 1be7bb9a 2024-09-05 continue self.footer = []
32 a7cabe95 2024-09-04 continue def on_data(self, data):
33 a7cabe95 2024-09-04 continue self.content.append(data.strip())
35 a7cabe95 2024-09-04 continue def flush(self):
36 f6854b29 2024-10-05 continue result = " ".join(" ".join(data.split()) for data in self.content if data)
37 1be7bb9a 2024-09-05 continue footer = self.footer
38 a7cabe95 2024-09-04 continue self.content = []
39 1be7bb9a 2024-09-05 continue self.footer = []
40 f6854b29 2024-10-05 continue return "\n".join([result] + footer) + "\n" if result else ""
43 a7cabe95 2024-09-04 continue class LinkTag(_BaseTag):
44 1be7bb9a 2024-09-05 continue def __init__(self, href, paragraph, tag, attrs):
45 a7cabe95 2024-09-04 continue super().__init__(tag, attrs)
46 1be7bb9a 2024-09-05 continue self.href = href
47 1be7bb9a 2024-09-05 continue self.paragraph = paragraph
48 a7cabe95 2024-09-04 continue self.content = []
50 a7cabe95 2024-09-04 continue def on_data(self, data):
51 1be7bb9a 2024-09-05 continue if not self.content:
52 1f653a98 2024-09-05 continue self.paragraph.on_data("↳")
53 1be7bb9a 2024-09-05 continue self.paragraph.on_data(data)
54 a7cabe95 2024-09-04 continue self.content.append(data.strip())
56 a7cabe95 2024-09-04 continue def flush(self):
57 1be7bb9a 2024-09-05 continue text = " ".join(" ".join(data.split()) for data in self.content if data)
58 1be7bb9a 2024-09-05 continue self.paragraph.footer.append(f"=> {self.href} {text}")
59 1be7bb9a 2024-09-05 continue return ""
62 280fbeb1 2024-10-11 continue class LiItemTag(ParagraphTag):
63 a7cabe95 2024-09-04 continue def flush(self):
64 a7cabe95 2024-09-04 continue content = super().flush()
65 a7cabe95 2024-09-04 continue return f"* {content}" if content else ""
68 a7cabe95 2024-09-04 continue class QuoteTag(ParagraphTag):
69 a7cabe95 2024-09-04 continue def flush(self):
70 a7cabe95 2024-09-04 continue content = super().flush()
71 a7cabe95 2024-09-04 continue return f"> {content}" if content else ""
74 ae087ef0 2024-09-04 continue class HeaderTag(ParagraphTag):
75 ae087ef0 2024-09-04 continue def flush(self):
76 ae087ef0 2024-09-04 continue content = super().flush()
77 ae087ef0 2024-09-04 continue if not content:
78 ae087ef0 2024-09-04 continue return ""
79 ae087ef0 2024-09-04 continue return f"{'#' * int(self.tag[1:])} {content}"
82 ae087ef0 2024-09-04 continue class PreformattedTag(_BaseTag):
83 ae087ef0 2024-09-04 continue def __init__(self, tag, attrs):
84 ae087ef0 2024-09-04 continue super().__init__(tag, attrs)
85 ae087ef0 2024-09-04 continue self.content = ""
87 ae087ef0 2024-09-04 continue def on_data(self, data):
88 ae087ef0 2024-09-04 continue self.content += data
90 ae087ef0 2024-09-04 continue def flush(self):
91 f6854b29 2024-10-05 continue result = self.content
92 ae087ef0 2024-09-04 continue self.content = ""
93 f6854b29 2024-10-05 continue return f"```\n{result}\n```\n" if result else ""
96 a7cabe95 2024-09-04 continue class HtmlToGmi(HTMLParser):
97 29500f51 2024-09-20 continue def __init__(self, base_url, fn_media_url):
98 a7cabe95 2024-09-04 continue super().__init__()
99 a7cabe95 2024-09-04 continue self.gmi_text = []
100 a7cabe95 2024-09-04 continue self.stack = []
101 1f653a98 2024-09-05 continue self.base_url = base_url
102 29500f51 2024-09-20 continue self.fn_media_url = fn_media_url
104 f6854b29 2024-10-05 continue def feed(self, data):
105 f6854b29 2024-10-05 continue super().feed(data)
106 a7cabe95 2024-09-04 continue while self.stack:
107 a7cabe95 2024-09-04 continue self.gmi_text.append(self.stack.pop().flush())
108 a7cabe95 2024-09-04 continue return "\n".join(gmi_text for gmi_text in self.gmi_text if gmi_text)
110 a7cabe95 2024-09-04 continue def handle_starttag(self, tag, attrs):
111 1b9c1500 2024-09-05 continue def _push(elem):
112 1b9c1500 2024-09-05 continue if self.stack:
113 1b9c1500 2024-09-05 continue self.gmi_text.append(self.stack[-1].flush())
114 1b9c1500 2024-09-05 continue self.stack.append(elem)
116 1b9c1500 2024-09-05 continue if tag == "p":
117 1b9c1500 2024-09-05 continue _push(ParagraphTag(tag, attrs))
118 1b9c1500 2024-09-05 continue elif tag == "pre":
119 1b9c1500 2024-09-05 continue _push(PreformattedTag(tag, attrs))
120 ae087ef0 2024-09-04 continue elif tag in {"h1", "h2", "h3", "h4", "h5", "h6"}:
121 1b9c1500 2024-09-05 continue _push(HeaderTag(tag, attrs))
122 ae087ef0 2024-09-04 continue elif tag in {"li", "dt"}:
123 280fbeb1 2024-10-11 continue _push(LiItemTag(tag, attrs))
124 ae087ef0 2024-09-04 continue elif tag in {"blockquote", "q"}:
125 1b9c1500 2024-09-05 continue _push(QuoteTag(tag, attrs))
126 a7cabe95 2024-09-04 continue elif tag == "a":
127 4e7950e1 2024-09-30 continue href = dict(attrs).get("href")
128 1be7bb9a 2024-09-05 continue if href:
129 1f653a98 2024-09-05 continue self.stack.append(LinkTag(urljoin(self.base_url, href), self._get_current_paragraph(), tag, attrs))
130 a7cabe95 2024-09-04 continue elif tag == "img":
131 4e7950e1 2024-09-30 continue img = dict(attrs)
132 1b9c1500 2024-09-05 continue title = img.get("title") or ""
133 1b9c1500 2024-09-05 continue if img.get("class") == "emu" and title and self.stack:
134 1b9c1500 2024-09-05 continue self.stack[-1].on_data(title)
136 1b9c1500 2024-09-05 continue src = img.get("src")
137 1b9c1500 2024-09-05 continue if src:
138 280fbeb1 2024-10-11 continue http_img_url = urljoin(self.base_url, src)
139 280fbeb1 2024-10-11 continue mime, _ = guess_type(http_img_url)
140 280fbeb1 2024-10-11 continue img_url = self.fn_media_url(mime, http_img_url)
141 280fbeb1 2024-10-11 continue self.gmi_text.append(f"=> {img_url} {title or http_img_url}")
142 5c749e57 2024-09-05 continue elif tag == "br":
143 5c749e57 2024-09-05 continue if self.stack:
144 5c749e57 2024-09-05 continue self.gmi_text.append(self.stack[-1].flush())
146 a7cabe95 2024-09-04 continue def handle_data(self, data):
147 a7cabe95 2024-09-04 continue if not self.stack:
148 1b9c1500 2024-09-05 continue self.stack.append(ParagraphTag("p", []))
149 a7cabe95 2024-09-04 continue self.stack[-1].on_data(data)
151 a7cabe95 2024-09-04 continue def handle_endtag(self, tag):
152 1b9c1500 2024-09-05 continue if self.stack and tag == self.stack[-1].tag:
153 1b9c1500 2024-09-05 continue self.gmi_text.append(self.stack.pop().flush())
155 1be7bb9a 2024-09-05 continue def _get_current_paragraph(self):
156 1be7bb9a 2024-09-05 continue for elem in reversed(self.stack):
157 1be7bb9a 2024-09-05 continue if isinstance(elem, ParagraphTag):
158 1be7bb9a 2024-09-05 continue return elem
160 1be7bb9a 2024-09-05 continue self.stack = [ParagraphTag("p", [])] + self.stack
161 1be7bb9a 2024-09-05 continue return self.stack[0]
164 e03b8dd3 2024-09-25 continue class LonkUrl:
165 e03b8dd3 2024-09-25 continue def __init__(self, raw_url):
166 e03b8dd3 2024-09-25 continue self._splitted_url = urlsplit(raw_url)
167 e03b8dd3 2024-09-25 continue self.splitted_path = [part for part in self._splitted_url.path.split("/") if part]
168 e03b8dd3 2024-09-25 continue self.page = self.splitted_path[-1]
169 e03b8dd3 2024-09-25 continue self._base_path = []
170 e03b8dd3 2024-09-25 continue for path_part in self.splitted_path:
171 e03b8dd3 2024-09-25 continue self._base_path.append(path_part)
172 e03b8dd3 2024-09-25 continue if path_part == "lonk":
175 e03b8dd3 2024-09-25 continue def build(self, page, query=""):
176 e03b8dd3 2024-09-25 continue page = page if isinstance(page, list) else [page]
177 e03b8dd3 2024-09-25 continue return urlunsplit(
178 e03b8dd3 2024-09-25 continue ("gemini", self._splitted_url.netloc, "/".join(self._base_path + page), query, "")
181 fafb2ce7 2024-10-02 continue def media(self, mime, url):
182 fafb2ce7 2024-10-02 continue return self.build("proxy", urlencode({"m": mime, "u": url})) if mime else url
184 e03b8dd3 2024-09-25 continue @property
185 e03b8dd3 2024-09-25 continue def query(self):
186 e03b8dd3 2024-09-25 continue return self._splitted_url.query
189 09255143 2024-09-25 continue class HonkUrl:
190 09255143 2024-09-25 continue def __init__(self, raw_url, token):
191 09255143 2024-09-25 continue self._splitted_url = urlsplit(raw_url)
192 09255143 2024-09-25 continue self._token = token
194 056d3709 2024-10-10 continue def build(self, scheme=None, netloc=None, path="", query="", fragment=""):
195 09255143 2024-09-25 continue return urlunsplit(
197 09255143 2024-09-25 continue scheme or self._splitted_url.scheme,
198 09255143 2024-09-25 continue netloc or self._splitted_url.netloc,
201 09255143 2024-09-25 continue fragment,
205 056d3709 2024-10-10 continue def get(self, action, answer_is_json=True, **kwargs):
206 c093e3cd 2024-10-13 continue start_time = clock_gettime(CLOCK_MONOTONIC)
208 c093e3cd 2024-10-13 continue query = {**{"action": action, "token": self._token}, **kwargs}
209 c093e3cd 2024-10-13 continue with urlopen(self.build(path="api", query=urlencode(query)), timeout=45) as response:
210 c093e3cd 2024-10-13 continue answer = response.read().decode("utf8")
211 c093e3cd 2024-10-13 continue return json_loads(answer) if answer_is_json else answer
212 c093e3cd 2024-10-13 continue finally:
213 c093e3cd 2024-10-13 continue stderr.write(f"GET {action} {kwargs}|{clock_gettime(CLOCK_MONOTONIC) - start_time:.3f}sec.\n")
216 280fbeb1 2024-10-11 continue def db_create_schema(db_con):
217 4acbf994 2024-09-25 continue db_con.execute(
219 577b12da 2024-09-24 continue CREATE TABLE
220 577b12da 2024-09-24 continue client (
221 c093e3cd 2024-10-13 continue cert_hash TEXT PRIMARY KEY,
222 577b12da 2024-09-24 continue honk_url TEXT NOT NULL,
223 577b12da 2024-09-24 continue token TEXT NOT NULL
229 4e7950e1 2024-09-30 continue def db_connect():
230 577b12da 2024-09-24 continue db_file_path = Path(__file__).parent / ".local" / "db"
231 577b12da 2024-09-24 continue db_file_path.parent.mkdir(parents=True, exist_ok=True)
232 577b12da 2024-09-24 continue db_exist = db_file_path.exists()
233 577b12da 2024-09-24 continue db_con = sqlite3_connect(db_file_path)
234 577b12da 2024-09-24 continue if not db_exist:
235 e03b8dd3 2024-09-25 continue with db_con:
236 280fbeb1 2024-10-11 continue db_create_schema(db_con)
237 577b12da 2024-09-24 continue return db_con
240 280fbeb1 2024-10-11 continue def print_header(page_name):
241 280fbeb1 2024-10-11 continue print("20 text/gemini\r")
242 280fbeb1 2024-10-11 continue print(f"# 𝓗 onk: {page_name}\r")
243 280fbeb1 2024-10-11 continue print("\r")
246 280fbeb1 2024-10-11 continue def print_menu(lonk_url, honk_url, gethonks_answer=None):
247 c8840e58 2024-10-13 continue print("## 📝 Menu\r")
248 280fbeb1 2024-10-11 continue print(f"=> {lonk_url.build('newhonk')} new honk\r")
249 280fbeb1 2024-10-11 continue print(f"=> {lonk_url.build([])} lonk home\r")
250 4bf100ff 2024-10-27 continue print(f"=> {lonk_url.build('first')} first class only\r")
252 280fbeb1 2024-10-11 continue if gethonks_answer:
253 280fbeb1 2024-10-11 continue line = f"=> {lonk_url.build('atme')} @me"
254 280fbeb1 2024-10-11 continue if gethonks_answer["mecount"]:
255 280fbeb1 2024-10-11 continue line += f' ({gethonks_answer["mecount"]})'
256 280fbeb1 2024-10-11 continue print(line + "\r")
258 280fbeb1 2024-10-11 continue line = f"=> {honk_url.build(path='chatter')} chatter"
259 280fbeb1 2024-10-11 continue if gethonks_answer["chatcount"]:
260 280fbeb1 2024-10-11 continue line += f' ({gethonks_answer["chatcount"]})'
261 280fbeb1 2024-10-11 continue print(line + "\r")
263 280fbeb1 2024-10-11 continue print(f"=> {lonk_url.build('search')} search\r")
264 280fbeb1 2024-10-11 continue print(f"=> {lonk_url.build('longago')} long ago\r")
265 280fbeb1 2024-10-11 continue print(f"=> {lonk_url.build('myhonks')} my honks\r")
266 280fbeb1 2024-10-11 continue print(f"=> {lonk_url.build('gethonkers')} honkers\r")
267 280fbeb1 2024-10-11 continue print(f"=> {lonk_url.build('addhonker')} add new honker\r")
270 280fbeb1 2024-10-11 continue def print_gethonks(gethonks_answer, lonk_url, honk_url):
271 280fbeb1 2024-10-11 continue print_menu(lonk_url, honk_url, gethonks_answer)
272 280fbeb1 2024-10-11 continue print("\r")
274 280fbeb1 2024-10-11 continue for honk in gethonks_answer.get("honks") or []:
275 280fbeb1 2024-10-11 continue convoy = honk["Convoy"]
276 280fbeb1 2024-10-11 continue re_url = honk.get("RID")
277 280fbeb1 2024-10-11 continue oondle = honk.get("Oondle")
278 280fbeb1 2024-10-11 continue from_ = f'{oondle} (🔁 {honk["Handle"]})' if oondle else f'{honk["Handle"]}'
279 280fbeb1 2024-10-11 continue lines = [
280 280fbeb1 2024-10-11 continue f'##{"# ↱" if re_url else ""} From {from_} {honk["Date"]}',
281 280fbeb1 2024-10-11 continue f'=> {lonk_url.build("convoy", urlencode({"c": convoy}))} Convoy {convoy}',
282 280fbeb1 2024-10-11 continue f'=> {honk["XID"]}',
284 280fbeb1 2024-10-11 continue if re_url:
285 280fbeb1 2024-10-11 continue lines.append(f'=> {re_url} Re: {re_url}')
286 280fbeb1 2024-10-11 continue lines.append("")
287 280fbeb1 2024-10-11 continue lines.append(HtmlToGmi(honk_url.build(), lonk_url.media).feed(honk["HTML"]))
288 280fbeb1 2024-10-11 continue for donk in honk.get("Donks") or []:
289 ff1d2e46 2024-10-21 continue if donk.get("XID"):
290 ff1d2e46 2024-10-21 continue donk_url = honk_url.build(path=f'/d/{donk["XID"]}')
292 ff1d2e46 2024-10-21 continue donk_url = urljoin(honk["XID"], donk["URL"])
293 ff1d2e46 2024-10-21 continue donk_mime = donk["Media"]
294 280fbeb1 2024-10-11 continue lines.append(f'=> {lonk_url.media(donk_mime, donk_url)} {donk_url}')
295 ff1d2e46 2024-10-21 continue donk_text = donk.get("Desc") or donk.get("Name") or None
296 280fbeb1 2024-10-11 continue if donk_text:
297 280fbeb1 2024-10-11 continue lines.append(donk_text)
298 280fbeb1 2024-10-11 continue lines.append("")
299 280fbeb1 2024-10-11 continue if honk.get("Public"):
300 280fbeb1 2024-10-11 continue lines.append(f'=> {lonk_url.build("bonk", urlencode({"w": honk["XID"]}))} ↺ bonk')
301 280fbeb1 2024-10-11 continue honk_back_url = lonk_url.build(
303 280fbeb1 2024-10-11 continue quote(honk["Handles"] or " ", safe=""),
304 280fbeb1 2024-10-11 continue quote(honk["XID"], safe=""),
305 280fbeb1 2024-10-11 continue "honkback",
308 280fbeb1 2024-10-11 continue lines.append(f'=> {honk_back_url} ↱ honk back')
309 280fbeb1 2024-10-11 continue for xonker in (honk.get("Honker"), honk.get("Oonker")):
310 280fbeb1 2024-10-11 continue if xonker:
311 280fbeb1 2024-10-11 continue lines.append(f'=> {lonk_url.build("honker", urlencode({"xid": xonker}))} honks of {xonker}')
312 280fbeb1 2024-10-11 continue print("\r\n".join(lines))
313 280fbeb1 2024-10-11 continue print("\r")
315 280fbeb1 2024-10-11 continue if gethonks_answer.get("honks"):
316 280fbeb1 2024-10-11 continue print("\r")
317 280fbeb1 2024-10-11 continue print_menu(lonk_url, honk_url, gethonks_answer)
320 8b4f10af 2024-10-03 continue class _LonkTreeItem:
321 5dfecba4 2024-10-23 continue def __init__(self, honk):
322 c093e3cd 2024-10-13 continue self.honk = honk
323 8b4f10af 2024-10-03 continue self.thread = []
325 8b4f10af 2024-10-03 continue def iterate_honks(self):
326 c093e3cd 2024-10-13 continue if self.honk is not None:
327 c093e3cd 2024-10-13 continue yield self.honk
328 c093e3cd 2024-10-13 continue yield from self.thread
331 c093e3cd 2024-10-13 continue def page_lonk(lonk_url, honk_url):
332 056d3709 2024-10-10 continue gethonks_answer = honk_url.get("gethonks", page="home")
334 5dfecba4 2024-10-23 continue timeline = {}
335 ed872adb 2024-10-25 continue lonk_tree = {}
336 ed872adb 2024-10-25 continue for i, honk in enumerate(reversed(gethonks_answer["honks"])):
337 ed872adb 2024-10-25 continue timeline.setdefault(honk["Convoy"], i)
338 277b69f7 2024-10-22 continue if honk.get("RID"):
339 ed872adb 2024-10-25 continue lonk_tree.setdefault(honk["Convoy"], _LonkTreeItem(None))
341 ed872adb 2024-10-25 continue lonk_tree[honk["Convoy"]] = _LonkTreeItem(honk)
343 ed872adb 2024-10-25 continue # fetch first 36 threads (without start honk)
344 ed872adb 2024-10-25 continue sorted_ = sorted(timeline.keys(), key=lambda convoy: timeline[convoy], reverse=True)
345 277b69f7 2024-10-22 continue correction_map = {}
346 ed872adb 2024-10-25 continue for convoy in [convoy for convoy in sorted_ if lonk_tree[convoy].honk is None][:36]:
347 ed872adb 2024-10-25 continue for honk in honk_url.get("gethonks", page="convoy", c=convoy)["honks"]:
348 ed872adb 2024-10-25 continue if not honk.get("RID"):
349 ed872adb 2024-10-25 continue if convoy != honk["Convoy"]:
350 277b69f7 2024-10-22 continue correction_map[convoy] = honk["Convoy"]
351 ed872adb 2024-10-25 continue tl_weight_1 = timeline.pop(convoy)
352 277b69f7 2024-10-22 continue convoy = honk["Convoy"]
353 ed872adb 2024-10-25 continue tl_weight_2 = timeline.get(convoy)
354 ed872adb 2024-10-25 continue timeline[convoy] = tl_weight_1 if tl_weight_2 is None else min(tl_weight_1, tl_weight_2)
356 ed872adb 2024-10-25 continue item = lonk_tree.get(convoy)
357 ed872adb 2024-10-25 continue if item is None:
358 ed872adb 2024-10-25 continue lonk_tree[convoy] = _LonkTreeItem(honk)
359 ed872adb 2024-10-25 continue elif item.honk is None:
360 ed872adb 2024-10-25 continue item.honk = honk
363 ed872adb 2024-10-25 continue # no thread start found
364 5dfecba4 2024-10-23 continue timeline.pop(convoy)
366 ed872adb 2024-10-25 continue # link answers to thread
367 277b69f7 2024-10-22 continue for honk in reversed(gethonks_answer.pop("honks")):
368 ed872adb 2024-10-25 continue if honk.get("RID"):
369 ed872adb 2024-10-25 continue item = lonk_tree.get(correction_map.get(honk["Convoy"], honk["Convoy"]))
370 ed872adb 2024-10-25 continue if item is not None:
371 ed872adb 2024-10-25 continue if item.honk is not None:
372 ed872adb 2024-10-25 continue item.thread.append(honk)
374 ed872adb 2024-10-25 continue # build honks for page
375 8b4f10af 2024-10-03 continue gethonks_answer["honks"] = []
376 ed872adb 2024-10-25 continue for convoy in sorted(timeline.keys(), key=lambda convoy: timeline[convoy], reverse=True):
377 ed872adb 2024-10-25 continue item = lonk_tree[convoy]
378 5dfecba4 2024-10-23 continue if item.honk is None:
379 ed872adb 2024-10-25 continue break # first unfetched
380 277b69f7 2024-10-22 continue gethonks_answer["honks"] += list(item.iterate_honks())
382 280fbeb1 2024-10-11 continue print_header("lonk home")
383 4bf100ff 2024-10-27 continue print_gethonks(gethonks_answer, lonk_url, honk_url)
386 4bf100ff 2024-10-27 continue def page_first(lonk_url, honk_url):
387 4bf100ff 2024-10-27 continue gethonks_answer = honk_url.get("gethonks", page="home")
388 4bf100ff 2024-10-27 continue gethonks_answer["honks"] = [honk for honk in gethonks_answer.pop("honks") if honk["What"] in {"bonked", "honked"}]
389 4bf100ff 2024-10-27 continue print_header("first class only")
390 8b4f10af 2024-10-03 continue print_gethonks(gethonks_answer, lonk_url, honk_url)
393 c093e3cd 2024-10-13 continue def page_convoy(lonk_url, honk_url):
394 895356d0 2024-10-01 continue query = {pair[0]: pair[1] for pair in parse_qsl(lonk_url.query)}
395 895356d0 2024-10-01 continue if "c" not in query:
396 895356d0 2024-10-01 continue print("51 Not found\r")
399 056d3709 2024-10-10 continue gethonks_answer = honk_url.get("gethonks", page="convoy", c=query["c"])
400 280fbeb1 2024-10-11 continue print_header(f"convoy {query['c']}")
401 8b4f10af 2024-10-03 continue print_gethonks(gethonks_answer, lonk_url, honk_url)
404 c093e3cd 2024-10-13 continue def page_search(lonk_url, honk_url):
405 2ff52a39 2024-10-09 continue if not lonk_url.query:
406 29cd802f 2024-10-09 continue print("10 What are we looking for?\r")
409 2ff52a39 2024-10-09 continue q = unquote(lonk_url.query)
410 056d3709 2024-10-10 continue gethonks_answer = honk_url.get("gethonks", page="search", q=q)
411 280fbeb1 2024-10-11 continue print_header(f"search - {q}")
412 2ff52a39 2024-10-09 continue print_gethonks(gethonks_answer, lonk_url, honk_url)
415 c093e3cd 2024-10-13 continue def page_atme(lonk_url, honk_url):
416 056d3709 2024-10-10 continue gethonks_answer = honk_url.get("gethonks", page="atme")
417 280fbeb1 2024-10-11 continue print_header("@me")
418 8b4f10af 2024-10-03 continue print_gethonks(gethonks_answer, lonk_url, honk_url)
421 c093e3cd 2024-10-13 continue def page_longago(lonk_url, honk_url):
422 056d3709 2024-10-10 continue gethonks_answer = honk_url.get("gethonks", page="longago")
423 280fbeb1 2024-10-11 continue print_header("long ago")
424 b5ebf4c7 2024-10-09 continue print_gethonks(gethonks_answer, lonk_url, honk_url)
427 c093e3cd 2024-10-13 continue def page_myhonks(lonk_url, honk_url):
428 056d3709 2024-10-10 continue gethonks_answer = honk_url.get("gethonks", page="myhonks")
429 280fbeb1 2024-10-11 continue print_header("my honks")
430 3601f1e9 2024-10-10 continue print_gethonks(gethonks_answer, lonk_url, honk_url)
433 c093e3cd 2024-10-13 continue def page_honker(lonk_url, honk_url):
434 3601f1e9 2024-10-10 continue xid = {pair[0]: pair[1] for pair in parse_qsl(lonk_url.query)}.get("xid")
435 3601f1e9 2024-10-10 continue if not xid:
436 3601f1e9 2024-10-10 continue print("51 Not found\r")
439 056d3709 2024-10-10 continue gethonks_answer = honk_url.get("gethonks", page="honker", xid=xid)
440 280fbeb1 2024-10-11 continue print_header(f"honks of {xid}")
441 3601f1e9 2024-10-10 continue print_gethonks(gethonks_answer, lonk_url, honk_url)
444 c093e3cd 2024-10-13 continue def bonk(lonk_url, honk_url):
445 f6854b29 2024-10-05 continue what = {pair[0]: pair[1] for pair in parse_qsl(lonk_url.query)}.get("w")
446 f6854b29 2024-10-05 continue if not what:
447 f6854b29 2024-10-05 continue print("51 Not found\r")
450 056d3709 2024-10-10 continue honk_url.get("zonkit", wherefore="bonk", what=what, answer_is_json=False)
451 3601f1e9 2024-10-10 continue print(f'30 {lonk_url.build("myhonks")}\r')
454 c093e3cd 2024-10-13 continue def gethonkers(lonk_url, honk_url):
455 280fbeb1 2024-10-11 continue print_header("honkers")
456 280fbeb1 2024-10-11 continue print_menu(lonk_url, honk_url)
458 056d3709 2024-10-10 continue honkers = honk_url.get("gethonkers").get("honkers") or []
459 3efde7cb 2024-10-10 continue for honker in honkers:
460 3efde7cb 2024-10-10 continue print(f'## {honker.get("Name") or honker["XID"]}\r')
461 3efde7cb 2024-10-10 continue for field_name, display_name in zip(("Name", "XID", "Flavor"), ("name", "url", "flavor")):
462 3efde7cb 2024-10-10 continue value = honker.get(field_name)
463 3efde7cb 2024-10-10 continue if value:
464 3efde7cb 2024-10-10 continue print(f'{display_name}: {value}\r')
465 3efde7cb 2024-10-10 continue if honker.get("Flavor") == "sub":
466 3efde7cb 2024-10-10 continue print(f'=> {lonk_url.build("unsubscribe", urlencode({"honkerid": honker["ID"]}))} unsubscribe\r')
468 3efde7cb 2024-10-10 continue print(f'=> {lonk_url.build("subscribe", urlencode({"honkerid": honker["ID"]}))} (re)subscribe\r')
469 280fbeb1 2024-10-11 continue print(f'=> {lonk_url.build("honker", urlencode({"xid": honker["XID"]}))} honks of {honker["XID"]}\r')
470 3efde7cb 2024-10-10 continue print('\r')
472 3efde7cb 2024-10-10 continue if honkers:
473 3efde7cb 2024-10-10 continue print("\r")
474 280fbeb1 2024-10-11 continue print_menu(lonk_url, honk_url)
477 c093e3cd 2024-10-13 continue def addhonker(lonk_url, honk_url):
478 3efde7cb 2024-10-10 continue if not lonk_url.query:
479 056d3709 2024-10-10 continue print("10 honker url: \r")
482 3efde7cb 2024-10-10 continue url = unquote(lonk_url.query)
484 056d3709 2024-10-10 continue honk_url.get("savehonker", url=url, answer_is_json=False)
485 3efde7cb 2024-10-10 continue print(f'30 {lonk_url.build("gethonkers")}\r')
486 3efde7cb 2024-10-10 continue except HTTPError as error:
487 280fbeb1 2024-10-11 continue print_header("add new honker")
488 280fbeb1 2024-10-11 continue print_menu(lonk_url, honk_url)
489 3efde7cb 2024-10-10 continue print("\r")
490 3efde7cb 2024-10-10 continue print('## Error\r')
491 3efde7cb 2024-10-10 continue print(f'> {error.fp.read().decode("utf8")}\r')
494 c093e3cd 2024-10-13 continue def unsubscribe(lonk_url, honk_url):
495 3efde7cb 2024-10-10 continue honkerid = {pair[0]: pair[1] for pair in parse_qsl(lonk_url.query)}.get("honkerid")
496 3efde7cb 2024-10-10 continue if not honkerid:
497 3efde7cb 2024-10-10 continue print("51 Not found\r")
500 3efde7cb 2024-10-10 continue url = unquote(lonk_url.query)
501 056d3709 2024-10-10 continue honk_url.get("savehonker", honkerid=honkerid, unsub="unsub", answer_is_json=False)
502 3efde7cb 2024-10-10 continue print(f'30 {lonk_url.build("gethonkers")}\r')
505 c093e3cd 2024-10-13 continue def subscribe(lonk_url, honk_url):
506 3efde7cb 2024-10-10 continue honkerid = {pair[0]: pair[1] for pair in parse_qsl(lonk_url.query)}.get("honkerid")
507 3efde7cb 2024-10-10 continue if not honkerid:
508 3efde7cb 2024-10-10 continue print("51 Not found\r")
511 3efde7cb 2024-10-10 continue url = unquote(lonk_url.query)
512 056d3709 2024-10-10 continue honk_url.get("savehonker", honkerid=honkerid, sub="sub", answer_is_json=False)
513 3efde7cb 2024-10-10 continue print(f'30 {lonk_url.build("gethonkers")}\r')
516 c093e3cd 2024-10-13 continue def newhonk(lonk_url, honk_url):
517 056d3709 2024-10-10 continue if not lonk_url.query:
518 056d3709 2024-10-10 continue print("10 let's make some noise: \r")
521 056d3709 2024-10-10 continue noise = unquote(lonk_url.query)
522 056d3709 2024-10-10 continue honk_url.get("honk", noise=noise, answer_is_json=False)
523 056d3709 2024-10-10 continue print(f'30 {lonk_url.build("myhonks")}\r')
526 c093e3cd 2024-10-13 continue def honkback(lonk_url, honk_url):
527 056d3709 2024-10-10 continue if not lonk_url.query:
528 056d3709 2024-10-10 continue handles = unquote(lonk_url.splitted_path[-3]).strip()
529 056d3709 2024-10-10 continue rid = unquote(lonk_url.splitted_path[-2])
530 056d3709 2024-10-10 continue print(f"10 Answer to {handles or rid}:\r")
533 056d3709 2024-10-10 continue noise = unquote(lonk_url.query)
534 056d3709 2024-10-10 continue rid = unquote(lonk_url.splitted_path[-2])
535 056d3709 2024-10-10 continue honk_url.get("honk", noise=noise, rid=rid, answer_is_json=False)
536 056d3709 2024-10-10 continue print(f'30 {lonk_url.build("myhonks")}\r')
539 895356d0 2024-10-01 continue def authenticated(cert_hash, lonk_url, fn_impl):
540 895356d0 2024-10-01 continue db_con = db_connect()
541 c093e3cd 2024-10-13 continue row = db_con.execute("SELECT honk_url, token FROM client WHERE cert_hash=?", (cert_hash, )).fetchone()
542 895356d0 2024-10-01 continue if not row:
543 895356d0 2024-10-01 continue print(f'30 {lonk_url.build("ask_server")}\r')
545 c093e3cd 2024-10-13 continue honk_url, token = row
546 895356d0 2024-10-01 continue with db_con:
547 c093e3cd 2024-10-13 continue fn_impl(lonk_url, HonkUrl(honk_url, token))
550 280fbeb1 2024-10-11 continue def new_client_stage_1_ask_server(lonk_url):
551 280fbeb1 2024-10-11 continue if not lonk_url.query:
552 280fbeb1 2024-10-11 continue print("10 Honk server URL\r")
554 280fbeb1 2024-10-11 continue splitted = urlsplit(unquote(lonk_url.query))
555 280fbeb1 2024-10-11 continue path = [quote(urlunsplit((splitted.scheme, splitted.netloc, "", "", "")), safe=""), "ask_username"]
556 280fbeb1 2024-10-11 continue print(f'30 {lonk_url.build(path)}\r')
559 280fbeb1 2024-10-11 continue def new_client_stage_2_ask_username(lonk_url):
560 280fbeb1 2024-10-11 continue if not lonk_url.query:
561 280fbeb1 2024-10-11 continue print("10 Honk user name\r")
563 280fbeb1 2024-10-11 continue if len(lonk_url.splitted_path) < 3:
564 280fbeb1 2024-10-11 continue print('59 Bad request\r')
566 280fbeb1 2024-10-11 continue quoted_server = lonk_url.splitted_path[-2]
567 280fbeb1 2024-10-11 continue path = [quoted_server, quote(unquote(lonk_url.query), safe=""), "ask_password"]
568 280fbeb1 2024-10-11 continue print(f'30 {lonk_url.build(path)}\r')
571 280fbeb1 2024-10-11 continue def new_client_stage_3_ask_password(cert_hash, lonk_url):
572 280fbeb1 2024-10-11 continue if not lonk_url.query:
573 280fbeb1 2024-10-11 continue print("11 Honk user password\r")
575 280fbeb1 2024-10-11 continue if len(lonk_url.splitted_path) < 4:
576 280fbeb1 2024-10-11 continue print('59 Bad request\r')
579 280fbeb1 2024-10-11 continue honk_url = unquote(lonk_url.splitted_path[-3])
580 280fbeb1 2024-10-11 continue post_data = {
581 280fbeb1 2024-10-11 continue "username": unquote(lonk_url.splitted_path[-2]),
582 280fbeb1 2024-10-11 continue "password": unquote(lonk_url.query),
583 280fbeb1 2024-10-11 continue "gettoken": "1",
585 280fbeb1 2024-10-11 continue with urlopen(honk_url + "/dologin", data=urlencode(post_data).encode(), timeout=15) as response:
586 280fbeb1 2024-10-11 continue token = response.read().decode("utf8")
587 280fbeb1 2024-10-11 continue db_con = db_connect()
588 280fbeb1 2024-10-11 continue with db_con:
589 280fbeb1 2024-10-11 continue db_con.execute(
590 c1a46592 2024-11-05 continue "INSERT OR REPLACE INTO client (cert_hash, honk_url, token) VALUES (?, ?, ?)",
591 280fbeb1 2024-10-11 continue (cert_hash, honk_url, token)
593 280fbeb1 2024-10-11 continue print(f'30 {lonk_url.build([])}\r')
596 b7194e03 2024-09-12 continue def proxy(mime, url):
597 f6854b29 2024-10-05 continue with urlopen(url, timeout=10) as response:
598 15efabff 2024-09-13 continue stdout.buffer.write(b"20 " + mime.encode() + b"\r\n")
599 15efabff 2024-09-13 continue while True:
600 f6854b29 2024-10-05 continue content = response.read(512 * 1024)
601 15efabff 2024-09-13 continue if not content:
603 15efabff 2024-09-13 continue stdout.buffer.write(content)
606 2d018e2b 2024-11-05 continue def vgi(cert_hash, lonk_url):
607 e03b8dd3 2024-09-25 continue if lonk_url.page == "lonk":
608 8b4f10af 2024-10-03 continue authenticated(cert_hash, lonk_url, page_lonk)
609 4bf100ff 2024-10-27 continue elif lonk_url.page == "first":
610 4bf100ff 2024-10-27 continue authenticated(cert_hash, lonk_url, page_first)
611 895356d0 2024-10-01 continue elif lonk_url.page == "convoy":
612 8b4f10af 2024-10-03 continue authenticated(cert_hash, lonk_url, page_convoy)
613 895356d0 2024-10-01 continue elif lonk_url.page == "atme":
614 8b4f10af 2024-10-03 continue authenticated(cert_hash, lonk_url, page_atme)
615 2ff52a39 2024-10-09 continue elif lonk_url.page == "search":
616 2ff52a39 2024-10-09 continue authenticated(cert_hash, lonk_url, page_search)
617 b5ebf4c7 2024-10-09 continue elif lonk_url.page == "longago":
618 b5ebf4c7 2024-10-09 continue authenticated(cert_hash, lonk_url, page_longago)
619 3601f1e9 2024-10-10 continue elif lonk_url.page == "myhonks":
620 3601f1e9 2024-10-10 continue authenticated(cert_hash, lonk_url, page_myhonks)
621 3601f1e9 2024-10-10 continue elif lonk_url.page == "honker":
622 3601f1e9 2024-10-10 continue authenticated(cert_hash, lonk_url, page_honker)
623 f6854b29 2024-10-05 continue elif lonk_url.page == "bonk":
624 f6854b29 2024-10-05 continue authenticated(cert_hash, lonk_url, bonk)
625 3efde7cb 2024-10-10 continue elif lonk_url.page == "gethonkers":
626 3efde7cb 2024-10-10 continue authenticated(cert_hash, lonk_url, gethonkers)
627 3efde7cb 2024-10-10 continue elif lonk_url.page == "addhonker":
628 3efde7cb 2024-10-10 continue authenticated(cert_hash, lonk_url, addhonker)
629 3efde7cb 2024-10-10 continue elif lonk_url.page == "unsubscribe":
630 3efde7cb 2024-10-10 continue authenticated(cert_hash, lonk_url, unsubscribe)
631 3efde7cb 2024-10-10 continue elif lonk_url.page == "subscribe":
632 3efde7cb 2024-10-10 continue authenticated(cert_hash, lonk_url, subscribe)
633 056d3709 2024-10-10 continue elif lonk_url.page == "newhonk":
634 056d3709 2024-10-10 continue authenticated(cert_hash, lonk_url, newhonk)
635 056d3709 2024-10-10 continue elif lonk_url.page == "honkback":
636 056d3709 2024-10-10 continue authenticated(cert_hash, lonk_url, honkback)
637 e03b8dd3 2024-09-25 continue elif lonk_url.page == "ask_server":
638 e03b8dd3 2024-09-25 continue new_client_stage_1_ask_server(lonk_url)
639 e03b8dd3 2024-09-25 continue elif lonk_url.page == "ask_username":
640 e03b8dd3 2024-09-25 continue new_client_stage_2_ask_username(lonk_url)
641 e03b8dd3 2024-09-25 continue elif lonk_url.page == "ask_password":
642 e03b8dd3 2024-09-25 continue new_client_stage_3_ask_password(cert_hash, lonk_url)
643 e03b8dd3 2024-09-25 continue elif lonk_url.page == "proxy":
644 e03b8dd3 2024-09-25 continue query = {pair[0]: pair[1] for pair in parse_qsl(lonk_url.query)}
645 b7194e03 2024-09-12 continue if "m" not in query or "u" not in query:
646 b7194e03 2024-09-12 continue print("51 Not found\r")
648 b7194e03 2024-09-12 continue proxy(mime=query["m"], url=query["u"])
650 b7194e03 2024-09-12 continue print("51 Not found\r")
653 ed872adb 2024-10-25 continue def main():
654 4e7950e1 2024-09-30 continue cert_hash_ = environ.get("VGI_CERT_HASH")
655 4e7950e1 2024-09-30 continue if cert_hash_:
656 2d018e2b 2024-11-05 continue input_url = input().strip()
657 671e2610 2024-11-05 continue lonk_url = LonkUrl(input_url)
659 4acbf994 2024-09-25 continue start_time = clock_gettime(CLOCK_MONOTONIC)
661 671e2610 2024-11-05 continue vgi(cert_hash_, lonk_url)
662 4acbf994 2024-09-25 continue finally:
663 4e7950e1 2024-09-30 continue stderr.write(f"{cert_hash_}|{input_url}|{clock_gettime(CLOCK_MONOTONIC) - start_time:.3f}sec.\n")
664 15efabff 2024-09-13 continue except HTTPError as error:
665 3efde7cb 2024-10-10 continue stderr.write(f"{error}\n")
666 ac15aa2c 2024-11-05 continue if error.code == 403:
667 ac15aa2c 2024-11-05 continue print("20 text/gemini\r")
668 ac15aa2c 2024-11-05 continue print(f"# 𝓗 onk\r")
669 ac15aa2c 2024-11-05 continue print("\r")
670 2d018e2b 2024-11-05 continue print(f"Remote server return {error.code}: {error.reason}\r")
671 ac15aa2c 2024-11-05 continue print("\r")
672 ac15aa2c 2024-11-05 continue print("The previously issued token has probably expired. You need to authenticate again:\r")
673 ac15aa2c 2024-11-05 continue print(f'=> {lonk_url.build("ask_server")}\r')
675 ac15aa2c 2024-11-05 continue print(f"43 Remote server return {error.code}: {error.reason}\r")
676 15efabff 2024-09-13 continue except URLError as error:
677 3efde7cb 2024-10-10 continue stderr.write(f"{error}\n")
678 15efabff 2024-09-13 continue print(f"43 Error while trying to access remote server: {error.reason}\r")
679 dd301323 2024-09-17 continue except TimeoutError as error:
680 3efde7cb 2024-10-10 continue stderr.write(f"{error}\n")
681 dd301323 2024-09-17 continue print(f"43 Error while trying to access remote server: {error}\r")
683 3efde7cb 2024-10-10 continue stderr.write("Certificate required\n")
684 b7194e03 2024-09-12 continue print("60 Certificate required\r")
687 ed872adb 2024-10-25 continue if __name__ == '__main__':