Spaces:
Running

archive / server.py
tuka1's picture
Server-side OG/Twitter meta tags for rich link previews on shared URLs
4c2adc3 verified
Raw History Blame Contribute Delete
63.1 kB
"""FastAPI search server for the gamer2 archive. Run: uvicorn search.server:app --reload --port 8000 Endpoints: GET / โ†’ single-page UI (static/index.html) GET /api/search โ†’ FTS5 search with filters & snippets GET /api/thread/{thread_id} โ†’ full thread (all posts in order) GET /api/forums โ†’ list of forums GET /api/stats โ†’ DB stats """ from __future__ import annotations import os import sqlite3 from pathlib import Path from typing import Optional import re from functools import lru_cache from bs4 import BeautifulSoup from fastapi import FastAPI, HTTPException, Query, Request from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.errors import RateLimitExceeded from slowapi.middleware import SlowAPIMiddleware from slowapi.util import get_remote_address BASE_DIR = Path(__file__).resolve().parent DB_PATH = Path(os.environ.get("GAMER_DB", BASE_DIR / "posts.db")) STATIC_DIR = BASE_DIR / "static" AVATAR_DIR = Path( os.environ.get( "GAMER_AVATARS", BASE_DIR.parent / "gamer2" / "static" / "user_avatar", ) ) EMOJI_DIR = Path( os.environ.get( "GAMER_EMOJIS", BASE_DIR.parent / "gamer2" / "static" / "gamer" / "forum_images", ) ) def db(): """Open a fresh read-only connection per request (sqlite handles concurrency fine). immutable=1 (not mode=ro) โ€” the DB was last written by bake_rich_html.py in WAL mode, which leaves it expecting to lock -shm/-wal files even on a "read-only" open. In the deployed Docker image posts.db lives on a user-non-writable mount, so any lock attempt errors with "attempt to write a readonly database". immutable=1 tells SQLite the file will not change and to skip locking entirely โ€” perfect for our use case where the DB is baked once at image-build time and never modified at runtime.""" uri = f"file:{DB_PATH}?immutable=1" conn = sqlite3.connect(uri, uri=True, check_same_thread=False) conn.row_factory = sqlite3.Row # Best-effort perf PRAGMAs. cache_size and temp_store both attempt a # schema write in some SQLite builds, which fails when the DB file is # not user-writable (e.g. in the deployed Docker image where posts.db # is owned by root and we run as an unprivileged user). mmap_size is # the most important one โ€” it lets SQLite map the DB into the address # space and read pages without going through the page cache. for pragma in ( "PRAGMA mmap_size = 1073741824", "PRAGMA cache_size = -262144", "PRAGMA temp_store = MEMORY", ): try: conn.execute(pragma) except sqlite3.OperationalError: pass return conn _HEBREW_PREFIXES = ("ื”", "ื‘", "ื•", "ืœ", "ืž", "ืฉ", "ื›") _HEBREW_LETTER_RE = re.compile(r"[ึ-ืฟ]") # Hebrew stopwords โ€” short, ultra-common words whose postings lists are # huge (millions of hits each). When they appear alongside other tokens # we drop them from the FTS query so the rare tokens dominate the AND # intersection; without this, a query like `ืื ื™ ืงื•ืคืฅ ื‘ื—ื“ืจ` had to scan # 100k+ postings just for "ืื ื™". Users who need the literal word can # wrap it in "double quotes" to bypass this filter. _HEBREW_STOPWORDS = frozenset({ # personal pronouns "ืื ื™", "ืืชื”", "ืืช", "ื”ื•ื", "ื”ื™ื", "ืื ื—ื ื•", "ืืชื", "ืืชืŸ", "ื”ื", "ื”ืŸ", # demonstratives / common particles "ื–ื”", "ื–ืืช", "ืืœื”", "ืืœื•", "ื›ืš", "ื›ื›ื”", "ืฉื", "ืคื”", "ื›ืืŸ", # prepositions / conjunctions / fillers "ืฉืœ", "ืขืœ", "ืขื", "ืืœ", "ื›ื™", "ืื", "ืื–", "ื’ื", "ืจืง", "ื›ืŸ", "ืœื", "ืื‘ืœ", "ืื•", "ื›ืœ", "ื›ืžื•", "ื™ืฉ", "ืื™ืŸ", "ื”ื™ื”", "ื”ื™ื•", "ืื—ืจ", "ืœืคื ื™", "ืื—ืจื™", "ื‘ื™ืŸ", "ืžื”", "ืžื™", "ืื™ืš", "ืœืžื”", "ืœื™", "ืœื•", "ืœื”", "ืœื ื•", "ืœื›ื", }) def _is_stopword(tok: str) -> bool: return tok in _HEBREW_STOPWORDS _QUOTED_RE = re.compile(r'"([^"]+)"') _BLOCKQUOTE_OPEN_RE = re.compile(r"<blockquote\b[^>]*>", re.IGNORECASE) _BLOCKQUOTE_CLOSE_RE = re.compile(r"</blockquote\s*>", re.IGNORECASE) _TAG_RE = re.compile(r"<[^>]+>") _SPECIAL_TOKEN_RE = re.compile(r"^(ื“ื™ืจื•ื’[<>=]|ืฉื ื”:|ืคื•ืจื•ื:|ื”ื•ื“ืขื”:|ื”ื›ื™:)") def _strip_quotes_from_html(html: str) -> str: """Strip <blockquote>โ€ฆ</blockquote> sections (including arbitrarily nested ones) from baked HTML, returning the post's body text โ€” i.e. everything outside quoted-reply blocks. Uses a depth counter rather than regex matching since regex can't pair nested tags correctly: the outermost <blockquote> contains all the quote chain, so we drop everything between depth 0 โ†’ 0 transitions.""" out: list[str] = [] depth = 0 i = 0 n = len(html) while i < n: opn = _BLOCKQUOTE_OPEN_RE.search(html, i) cls = _BLOCKQUOTE_CLOSE_RE.search(html, i) if opn is None and cls is None: if depth == 0: out.append(html[i:]) break if opn is not None and (cls is None or opn.start() < cls.start()): if depth == 0: out.append(html[i:opn.start()]) depth += 1 i = opn.end() else: depth = max(0, depth - 1) i = cls.end() # type: ignore[union-attr] return _TAG_RE.sub(" ", "".join(out)) def _query_terms(q: str) -> list[str]: """Pull bare search terms out of user input โ€” quoted phrases and bare words, minus the structured tokens (ื“ื™ืจื•ื’>80, ืฉื ื”:2014, ...) that don't contribute to the FTS body match.""" terms: list[str] = [] def _take_phrase(m: re.Match) -> str: phrase = m.group(1).strip() if phrase: terms.append(phrase) return " " remainder = _QUOTED_RE.sub(_take_phrase, q) for tok in remainder.split(): if _SPECIAL_TOKEN_RE.match(tok): continue tok = tok.replace('"', "").strip() if tok: terms.append(tok) return terms def _term_present_in_body(body_text_lower: str, term: str) -> bool: """Check if a search term (or any one-letter Hebrew prefix variant of it) is present in body text. Mirrors the prefix-expansion that escape_fts() does so the body-match check stays in sync with what FTS would have actually matched.""" if term.lower() in body_text_lower: return True if _HEBREW_LETTER_RE.search(term): for p in _HEBREW_PREFIXES: if (p + term).lower() in body_text_lower: return True return False def _first_term_pos(body_lower: str, terms: list[str]) -> int: """Return the position of the earliest matching term in body_lower, or -1 if none of the terms appear.""" best = -1 for term in terms: variants = [term.lower()] if _HEBREW_LETTER_RE.search(term): variants += [(p + term).lower() for p in _HEBREW_PREFIXES] for v in variants: pos = body_lower.find(v) if pos != -1 and (best == -1 or pos < best): best = pos return best def _strip_quote_headers_text(text: str) -> str: """Strip serialized quote-header blocks from plain text content. Used as a fallback for posts whose HTML hasn't been baked yet โ€” without structure we can't tell where a quoted reply ends, but we can at least drop the 'ื ื›ืชื‘ ืข"ื™ <user> ื‘ืชืืจื™ืš <date>' / 'ืฆื™ื˜ื•ื˜ ืฉืœ <user> ืžืชื•ืš ื”ื•ื“ืขื” ืž <date>' header chunks so the visible snippet is the post text itself, not the quote chain metadata.""" lines = text.split("\n") out = [] i = 0 while i < len(lines): stripped = lines[i].strip() if stripped == 'ื ื›ืชื‘ ืข"ื™' and i + 2 < len(lines): i += 3 # skip "ื ื›ืชื‘ ืข"ื™", username, "ื‘ืชืืจื™ืš <date>" continue if stripped == "ืฆื™ื˜ื•ื˜ ืฉืœ" and i + 2 < len(lines): i += 3 continue out.append(lines[i]) i += 1 return "\n".join(out) def _build_snippet(body: str, terms: list[str], window: int = 320) -> str: """Build a context window centered on the first matching term. If no term appears in `body`, return the start of `body` (truncated).""" body = re.sub(r"\s+", " ", body).strip() if not body: return "" pos = _first_term_pos(body.lower(), terms) if pos == -1: s = body[:window] return s + ("โ€ฆ" if len(body) > window else "") half = window // 2 start = max(0, pos - half) end = min(len(body), start + window) s = body[start:end] if start > 0: s = "โ€ฆ" + s.lstrip() if end < len(body): s = s.rstrip() + "โ€ฆ" return s # Rating-bar colors that signify the top "elite positive" tiers. These have # G <= R numerically (so the simple G>R green-dominance check excludes them) # but in the original forum's palette they represent the highest-praise tiers # (magenta=0x990099, olive=0x323000 โ€” both only ever paired with dsize=100). _POSITIVE_ELITE_COLORS = (0x990099, 0x323000) _POS_FILTER = ( "(((p.color >> 8) & 0xFF) > ((p.color >> 16) & 0xFF) " f"OR p.color IN ({','.join(str(c) for c in _POSITIVE_ELITE_COLORS)}))" ) # Sort key that puts elite colors above the green-dominant ones, breaking ties # by dsize and recency. _POS_ORDER = ( "CASE p.color " f"WHEN {0x990099} THEN 3 " f"WHEN {0x323000} THEN 2 " "ELSE 1 END DESC, p.dsize DESC, p.created_at DESC" ) def escape_fts(q: str) -> str: """Build an FTS5 MATCH expression from user input. Anything inside paired double-quotes is treated as an EXACT phrase (no prefix-letter expansion, no wildcard suffix) โ€” e.g. `"red dead"` matches the phrase literally. Outside quotes, each whitespace-separated token: * If it contains Hebrew, expands to an OR of variants โ€” the bare token plus the same token with each common one-letter prefix (ื”/ื‘/ื•/ืœ/ืž/ืฉ/ื›). Each variant gets a `*` suffix so suffixed forms also match (e.g. "ื’ื•ืžืœ" โ†’ "ื’ื•ืžืœ*" matches ื’ื•ืžืœืช/ื’ื•ืžืœื™ื, "ื”ื’ื•ืžืœ*" matches ื”ื’ื•ืžืœืช). * Non-Hebrew tokens get the same prefix-wildcard treatment but no prefix-letter expansion. Hebrew stopwords (ืื ื™ / ืฉืœ / ืขืœ / โ€ฆ) are dropped when there are other tokens โ€” their postings lists are too big to AND-intersect efficiently and they add no selectivity. Users who need them literally can quote. Quoting + bareword sanitization keeps user input safe inside the FTS5 MATCH grammar.""" parts: list[str] = [] # First, pull out quoted phrases and add them as exact FTS phrase matches. def _take_phrase(m: re.Match) -> str: phrase = m.group(1).replace('"', "").strip() if phrase: parts.append(f'"{phrase}"') return " " remainder = _QUOTED_RE.sub(_take_phrase, q) # Two-pass over bare tokens so we know if we have non-stopword content # before deciding whether to drop the stopwords. raw_tokens = [t.replace('"', "").strip() for t in remainder.split()] bare_tokens = [t for t in raw_tokens if t] non_stop = [t for t in bare_tokens if not _is_stopword(t)] # Drop stopwords only if at least one non-stopword survives โ€” otherwise # a query like just "ืื ื™" would return no results at all. tokens = non_stop if non_stop else bare_tokens for tok in tokens: if _HEBREW_LETTER_RE.search(tok): variants = [tok] for p in _HEBREW_PREFIXES: if not tok.startswith(p): variants.append(p + tok) ored = " OR ".join(f'"{v}"*' for v in variants) parts.append(f"({ored})") else: parts.append(f'"{tok}"*') return " AND ".join(parts) if parts else "" app = FastAPI(title="gamer2 archive search") # ---------- rate limiting ---------- # Per-IP sliding-window limits, applied to every route via SlowAPIMiddleware. # 120/min is generous for normal interactive use (~2 req/sec); trips on abuse. limiter = Limiter(key_func=get_remote_address, default_limits=["120/minute"]) app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) app.add_middleware(SlowAPIMiddleware) # ---------- rich HTML extraction (on-demand from source files) ---------- # Tags we keep when serving the rich representation. Everything else is stripped # (its contents survive). We keep blockquote so the forum-style quote rendering # works, formatting tags for fidelity, and br/p for layout. _ALLOWED_TAGS = { "blockquote", "b", "strong", "i", "em", "u", "p", "br", "hr", "div", "span", "font", "ul", "ol", "li", "table", "tr", "td", "th", "img", "a", } _ALLOWED_ATTRS = { "a": {"href", "title"}, "img": {"src", "alt", "width", "height", "title"}, "div": {"dir", "style", "class"}, "span": {"dir", "style"}, "font": {"color", "face", "size"}, "p": {"dir"}, "blockquote": {"dir", "data-quote-author", "data-quote-time"}, } _SCRIPT_TAGS = {"script", "style", "noscript", "iframe", "object", "embed"} # Within a `style` attribute, only these CSS properties are kept. Anything # else (position:fixed overlays, transform tricks, url() expressions, etc.) # is dropped. _ALLOWED_CSS_PROPS = {"background-color", "color"} _CSS_DECL_RE = re.compile(r"([a-zA-Z-]+)\s*:\s*([^;]+)") def _sanitize_style(value: str) -> str: """Keep only allowlisted CSS properties; drop anything else.""" out = [] for m in _CSS_DECL_RE.finditer(value or ""): prop = m.group(1).strip().lower() val = m.group(2).strip() if prop not in _ALLOWED_CSS_PROPS: continue # Defensive: reject any value containing url() / expression() / # javascript: in case a weird future browser tries to execute it. low = val.lower() if "url(" in low or "expression(" in low or "javascript:" in low: continue out.append(f"{prop}: {val}") return "; ".join(out) _REPLY_PATTERN = re.compile(r"^Reply(\d+)$") # Quote headers come in two flavors: # "ืฆื™ื˜ื•ื˜ ืฉืœ <b>NICK</b> ืžืชื•ืš ื”ื•ื“ืขื” ืž YYYY-MM-DD HH:MM:SS" # "ื ื›ืชื‘ ืข"ื™ <a href=...>NICK</a> ื‘ืชืืจื™ืš YYYY-MM-DD HH:MM:SS" _QUOTE_HEADER_RES = [ re.compile(r"ืฆื™ื˜ื•ื˜ ืฉืœ\s*(?:<[^>]+>)?\s*(?P<nick>[^<\n]+?)\s*(?:</[^>]+>)?\s*ืžืชื•ืš ื”ื•ื“ืขื” ืž\s*(?P<ts>\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})"), re.compile(r"ื ื›ืชื‘ ืข\"ื™\s*(?:<[^>]+>)?\s*(?P<nick>[^<\n]+?)\s*(?:</[^>]+>)?\s*ื‘ืชืืจื™ืš\s*(?P<ts>\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})"), ] # rewrite gamer-hosted asset urls to our local mounts _EMOJI_URL_RE = re.compile(r"https?://[^/]*gamer[^/]*/(?:gamer/)?forum_images/([^\"' >]+)") _AVATAR_URL_RE = re.compile(r"(?:https?://[^/]*gamer[^/]*/)?(?:\.\./)*user_avatar/(user\d+\.jpg)", re.I) def _rewrite_asset_url(src: str) -> str: if not src: return src m = _EMOJI_URL_RE.search(src) if m: return "/forum_emojis/" + m.group(1) m = _AVATAR_URL_RE.search(src) if m: return "/avatars/" + m.group(1) return src def _annotate_quote_blocks(soup, node): """Normalize <blockquote> structure and tag with data-quote-author/time. Forum blockquotes come in two flavors: Old (2004-2007): <blockquote><div>ืฆื™ื˜ื•ื˜ ืฉืœ X ืžืชื•ืš ื”ื•ื“ืขื” ืž DATE</div><hr/><div>body</div></blockquote> Newer (2010+): <blockquote>ื ื›ืชื‘ ืข"ื™ <a>X</a> ื‘ืชืืจื™ืš DATE<hr/>body<hr/></blockquote> (children are raw text/anchors, separated by <hr/>, no wrapping divs) We split each blockquote at the FIRST <hr/>, wrap the head in <div class="quote-head"> and the rest in <div class="quote-body">, and drop the separators. That gives the client a single, predictable structure to style and to handle clicks on (jump-to-quoted-post).""" from bs4 import NavigableString for bq in list(node.find_all("blockquote")): children = list(bq.children) # find first <hr> separator (or fall back: no split, treat first # text/inline run as head) split_idx = None for i, ch in enumerate(children): if getattr(ch, "name", None) == "hr": split_idx = i break if split_idx is None: head_children = [] body_children = children else: head_children = children[:split_idx] body_children = children[split_idx + 1 :] # Strip a trailing <hr/> from the body (closing separator in new format) while body_children and getattr(body_children[-1], "name", None) == "hr": body_children = body_children[:-1] # Extract author+time from head text (works for either format) head_html = "".join( (c.decode() if hasattr(c, "decode") else str(c)) for c in head_children ) nick = ts = None for pat in _QUOTE_HEADER_RES: m = pat.search(head_html) if m: nick = m.group("nick").strip() ts = m.group("ts").strip() break # Rebuild: <blockquote><div class="quote-head">โ€ฆ</div><div class="quote-body">โ€ฆ</div></blockquote> bq.clear() if nick: bq["data-quote-author"] = nick if ts: bq["data-quote-time"] = ts head_div = soup.new_tag("div") head_div["class"] = "quote-head" for c in head_children: if getattr(c, "name", None) == "hr": continue head_div.append(c.extract() if hasattr(c, "extract") else NavigableString(str(c))) if len(list(head_div.children)) or nick: bq.append(head_div) body_div = soup.new_tag("div") body_div["class"] = "quote-body" for c in body_children: body_div.append(c.extract() if hasattr(c, "extract") else NavigableString(str(c))) bq.append(body_div) def _sanitize(node): """In-place sanitization: drop disallowed tags & attributes; unwrap the rest.""" for tag in list(node.find_all(True)): # An ancestor may have been decomposed in a prior iteration โ€” skip # detached nodes to avoid BS4's "not part of a tree" ValueError. if tag.parent is None: continue if tag.name in _SCRIPT_TAGS: tag.decompose() continue if tag.name not in _ALLOWED_TAGS: try: tag.unwrap() except ValueError: pass continue allowed = _ALLOWED_ATTRS.get(tag.name, set()) for attr in list(tag.attrs.keys()): if attr not in allowed: del tag.attrs[attr] # neuter javascript: links if tag.name == "a": href = tag.attrs.get("href", "") if href.lower().startswith(("javascript:", "data:")): tag.attrs["href"] = "#" # rewrite gamer-hosted asset URLs to our local mounts if tag.name == "img" and "src" in tag.attrs: tag.attrs["src"] = _rewrite_asset_url(tag.attrs["src"]) # tighten style attributes to a CSS allowlist (kills overlay/expr risks) if "style" in tag.attrs: cleaned = _sanitize_style(tag.attrs["style"]) if cleaned: tag.attrs["style"] = cleaned else: del tag.attrs["style"] def _sibling_page_files(file_path: str) -> list: """Given any one of the (possibly paginated) HTML files for a thread, return all sibling files for that thread on disk. Threads in batches 70-100 are split into 'replieslist.php@TopicID=N', 'replieslist.php@TopicID=N&page=1', '...&page=2', etc. We need all of them to render rich HTML for every post.""" if not file_path: return [] p = Path(file_path) m = re.search(r"TopicID=(\d+)", p.name) if not m: return [file_path] tid = m.group(1) # match the base file and all &page=N siblings pattern = re.compile(rf"TopicID={tid}(?:&page=\d+)?$|TopicID={tid}&|TopicID={tid}\Z") siblings = [] try: for entry in os.scandir(p.parent): if entry.is_file() and pattern.search(entry.name): siblings.append(str(Path(entry.path))) except OSError: return [file_path] return siblings or [file_path] @lru_cache(maxsize=64) def _parse_thread_html(file_path: str): """Returns dict[post_id] -> sanitized rich HTML string. Cached by file path since one file holds an entire thread; opening a post then the thread of that post would otherwise parse the same file twice.""" out = {} try: with open(file_path, "rb") as f: soup = BeautifulSoup(f, "html5lib") except FileNotFoundError: return out for div in soup.find_all("div", id=_REPLY_PATTERN): m = _REPLY_PATTERN.match(div["id"]) if not m: continue pid = int(m.group(1)) _annotate_quote_blocks(soup, div) _sanitize(div) # decode_contents returns the inner HTML html = div.decode_contents() # strip the spammed "Eliran Pe'er" link html = html.replace( "<a href=\"http://cookiesession.com/ืขืœื™ื ื•/ืืœื™ืจืŸ-ืคืืจ/\">Eliran Pe'er ืืœื™ืจืŸ ืคืืจ</a>", "", ) # rewrite relative avatar/file urls? keep as-is for now. out[pid] = html return out def _post_html(file_path: str, post_id: int): return _parse_thread_html(file_path).get(post_id, "") def _search_threads(conn, q, forum, author, date_from, date_to, sort, limit, offset, cursor=None): """Thread-scoped search. Matches the thread title (LIKE) and shows aggregated stats (first/last post, post count). Author/date filters are applied at the post level โ€” a thread is included only if it has matching posts under those filters.""" cur = conn.cursor() # Date filters operate at post level (thread included if it has any post # in the date range). Author filter is special โ€” in thread scope it means # "threads opened by this user", i.e. the user wrote the first post. post_filters = ["1=1"] post_params: list = [] if date_from: post_filters.append("p.created_at >= ?") post_params.append(date_from) if date_to: post_filters.append("p.created_at < ?") post_params.append(date_to) thread_filters = [] thread_params: list = [] if q: # Tokenize the title query like escape_fts does: quoted phrases stay # as single substrings; bare tokens are AND-ed individually so word # order and gaps don't matter (a query like `ืื ื™ ืงื•ืคืฅ ื‘ื—ื“ืจ` matches # a title `ืื ื™ ืงื•ืคืฅ ืขื›ืฉื™ื• ื‘ื—ื“ืจ`). Drop stopwords so they don't add # selectivity-free LIKEs. like_terms: list[str] = [] def _take(m: re.Match) -> str: phrase = m.group(1).replace('"', "").strip() if phrase: like_terms.append(phrase) return " " remainder = _QUOTED_RE.sub(_take, q) bare = [t.replace('"', "").strip() for t in remainder.split() if t.strip()] non_stop = [t for t in bare if not _is_stopword(t)] like_terms.extend(non_stop if non_stop else bare) if not like_terms: like_terms.append(q) # fallback (shouldn't trigger in practice) for term in like_terms: thread_filters.append("t.name LIKE ?") thread_params.append(f"%{term}%") if forum is not None: thread_filters.append("t.forum_id = ?") thread_params.append(forum) if date_from or date_to: thread_filters.append( f"t.id IN (SELECT p.thread_id FROM posts p WHERE {' AND '.join(post_filters)})" ) thread_params.extend(post_params) if author is not None: # Uses materialized t.first_author_id (set by build_index / maintenance) thread_filters.append("t.first_author_id = ?") thread_params.append(author) # Cursor pagination (O(1) for next/prev) โ€” relies on the materialized # t.first_post_at column. if cursor and sort in ("newest", "oldest"): try: c_at, c_id = cursor.rsplit("|", 1) c_id = int(c_id) cmp = "<" if sort == "newest" else ">" thread_filters.append(f"(t.first_post_at, t.id) {cmp} (?, ?)") thread_params.append(c_at) thread_params.append(c_id) except ValueError: pass where = " AND ".join(thread_filters) if thread_filters else "1=1" order = { "newest": "t.first_post_at DESC, t.id DESC", "oldest": "t.first_post_at ASC, t.id ASC", "relevance": "t.post_count DESC, t.first_post_at DESC", }[sort] sql = f""" SELECT t.id, t.name, t.forum_id, t.archive, f.name AS forum_name, t.first_post_at AS first_post, t.last_post_at AS last_post, t.post_count AS post_count, t.first_author_id, u.nick AS first_author_nick, (SELECT substr(p.content, 1, 200) FROM posts p WHERE p.thread_id = t.id ORDER BY p.idx LIMIT 1) AS first_excerpt FROM threads t LEFT JOIN forums f ON f.id = t.forum_id LEFT JOIN users u ON u.id = t.first_author_id WHERE {where} ORDER BY {order} LIMIT ? OFFSET ? """ effective_offset = 0 if cursor else offset rows = cur.execute(sql, thread_params + [limit, effective_offset]).fetchall() if cursor: total = -1 else: total = cur.execute( f"SELECT COUNT(*) FROM threads t WHERE {where}", thread_params ).fetchone()[0] rds = [dict(r) for r in rows] next_cursor = prev_cursor = None if rds and sort in ("newest", "oldest"): first = rds[0]; last = rds[-1] prev_cursor = f"{first.get('first_post') or ''}|{first.get('id') or 0}" next_cursor = f"{last.get('first_post') or ''}|{last.get('id') or 0}" return { "scope": "threads", "total": total, "limit": limit, "offset": offset, "next_cursor": next_cursor, "prev_cursor": prev_cursor, "results": rds, } @app.get("/api/search") def search( q: str = Query("", description="Search query (FTS5)"), scope: str = Query("posts", pattern="^(posts|threads)$"), forum: Optional[int] = Query(None), author: Optional[int] = Query(None), date_from: Optional[str] = Query(None, description="ISO date, inclusive"), date_to: Optional[str] = Query(None, description="ISO date, exclusive"), sort: str = Query("newest", pattern="^(relevance|newest|oldest|top_rated|top_hated)$"), limit: int = Query(30, ge=1, le=100), offset: int = Query(0, ge=0), cursor: Optional[str] = Query(None, description="Stable cursor 'created_at|id' for O(1) next/prev pagination"), rating_min: Optional[int] = Query(None, ge=0, le=100, description="Post star-rating bar fill %, lower bound (inclusive)"), rating_max: Optional[int] = Query(None, ge=0, le=100, description="Post star-rating bar fill %, upper bound (inclusive)"), idx: Optional[int] = Query(None, ge=1, description="Post index within thread (1 = first post)"), ): q = (q or "").strip() conn = db() try: if scope == "threads": return _search_threads(conn, q, forum, author, date_from, date_to, sort, limit, offset, cursor) cur = conn.cursor() # ------- Branch 1: text search โ†’ use FTS5 ------- if q: fts_q = escape_fts(q) where = ["posts_fts MATCH ?"] params: list = [fts_q] join_filters = [] if forum is not None: join_filters.append("t.forum_id = ?") params.append(forum) if author is not None: join_filters.append("p.author_id = ?") params.append(author) if date_from: join_filters.append("p.created_at >= ?") params.append(date_from) if date_to: join_filters.append("p.created_at < ?") params.append(date_to) if rating_min is not None: join_filters.append("p.dsize >= ?") params.append(rating_min) if rating_max is not None: join_filters.append("p.dsize <= ?") params.append(rating_max) if idx is not None: join_filters.append("p.idx = ?") params.append(idx) # Cursor pagination โ€” O(1) next/prev instead of slow OFFSET. # Cursor format: "created_at|post_id" (post_id breaks ties for # rows with equal created_at). if cursor and sort in ("newest", "oldest"): try: c_at, c_id = cursor.rsplit("|", 1) c_id = int(c_id) cmp = "<" if sort == "newest" else ">" join_filters.append(f"(p.created_at, p.id) {cmp} (?, ?)") params.append(c_at) params.append(c_id) except ValueError: pass order = { "relevance": "rank", "newest": "p.created_at DESC, p.id DESC", "oldest": "p.created_at ASC, p.id ASC", }[sort] # The original forum's star bar encodes vote direction in the BAR # COLOR โ€” green-ish = liked, brown-ish = hated. dsize alone doesn't # distinguish them, so for top_rated/top_hated we (a) filter by # color channel sign (G byte vs R byte) and (b) sort by dsize. if sort == "top_rated": join_filters.append(_POS_FILTER) join_filters.append("p.dsize > 0") elif sort == "top_hated": join_filters.append("((p.color >> 16) & 0xFF) > ((p.color >> 8) & 0xFF)") join_filters.append("p.dsize > 0") order_indexed = { "relevance": "p.created_at DESC, p.id DESC", # FTS rank doesn't apply with this plan "newest": "p.created_at DESC, p.id DESC", "oldest": "p.created_at ASC, p.id ASC", "top_rated": _POS_ORDER, "top_hated": "p.dsize DESC, p.created_at DESC", }[sort] sql = f""" SELECT p.id AS post_id, p.thread_id, p.author_id, p.idx, p.created_at, p.color AS post_color, p.dsize AS post_dsize, p.rank_desc, p.rank_color, p.rank_dsize, t.name AS thread_name, t.forum_id, f.name AS forum_name, u.nick AS author_nick, u.location AS author_location, u.messagecount AS author_messagecount, substr(p.content, 1, 320) AS snippet, p.content_html AS _content_html, t.file_path AS _file_path, t.name AS title_snippet FROM posts p INDEXED BY posts_created JOIN threads t ON t.id = p.thread_id LEFT JOIN forums f ON f.id = t.forum_id LEFT JOIN users u ON u.id = p.author_id WHERE p.id IN (SELECT rowid FROM posts_fts WHERE {" AND ".join(where)}) {(' AND ' + ' AND '.join(join_filters)) if join_filters else ''} ORDER BY {order_indexed} LIMIT ? OFFSET ? """ effective_offset = 0 if cursor else offset # Over-fetch so we can tier-sort (body match > unknown > quote-only) # across a larger window than one page. Without this, quote-only # hits on page N stay on page N even though direct hits exist # right behind them in natural order. fetch_limit = limit * 3 if sort in ("newest", "oldest", "relevance") else limit rows = cur.execute(sql, params + [fetch_limit, effective_offset]).fetchall() # COUNT is expensive when filters apply (full join scan). Skip on # cursor pages; cap at 10001 otherwise so "584K matches" doesn't # take seconds. Also skip for top_rated/top_hated โ€” the color # expression forces a per-row scan and pushes COUNT into multi- # second territory even with the cap. UI shows "โ€”" for total=-1. if cursor or sort in ("top_rated", "top_hated"): total = -1 else: count_params = list(params) count_sql = f""" SELECT COUNT(*) FROM ( SELECT 1 FROM posts_fts JOIN posts p ON p.id = posts_fts.rowid JOIN threads t ON t.id = p.thread_id WHERE {" AND ".join(where + join_filters)} LIMIT 10001 ) """ total = cur.execute(count_sql, count_params).fetchone()[0] # ------- Branch 2: no text search โ†’ metadata filter only ------- else: where = ["1=1"] params = [] if forum is not None: where.append("t.forum_id = ?") params.append(forum) if author is not None: where.append("p.author_id = ?") params.append(author) if date_from: where.append("p.created_at >= ?") params.append(date_from) if date_to: where.append("p.created_at < ?") params.append(date_to) if rating_min is not None: where.append("p.dsize >= ?") params.append(rating_min) if rating_max is not None: where.append("p.dsize <= ?") params.append(rating_max) if idx is not None: where.append("p.idx = ?") params.append(idx) if cursor and sort in ("newest", "oldest"): try: c_at, c_id = cursor.rsplit("|", 1) c_id = int(c_id) cmp = "<" if sort == "newest" else ">" where.append(f"(p.created_at, p.id) {cmp} (?, ?)") params.append(c_at) params.append(c_id) except ValueError: pass # See notes above: rating bar color encodes vote direction if sort == "top_rated": where.append(_POS_FILTER) where.append("p.dsize > 0") elif sort == "top_hated": where.append("((p.color >> 16) & 0xFF) > ((p.color >> 8) & 0xFF)") where.append("p.dsize > 0") order = { "oldest": "p.created_at ASC, p.id ASC", "top_rated": _POS_ORDER, "top_hated": "p.dsize DESC, p.created_at DESC", }.get(sort, "p.created_at DESC, p.id DESC") sql = f""" SELECT p.id AS post_id, p.thread_id, p.author_id, p.idx, p.created_at, p.color AS post_color, p.dsize AS post_dsize, p.rank_desc, p.rank_color, p.rank_dsize, t.name AS thread_name, t.forum_id, f.name AS forum_name, u.nick AS author_nick, u.location AS author_location, u.messagecount AS author_messagecount, substr(p.content, 1, 280) AS snippet, p.content_html AS _content_html, t.name AS title_snippet FROM posts p JOIN threads t ON t.id = p.thread_id LEFT JOIN forums f ON f.id = t.forum_id LEFT JOIN users u ON u.id = p.author_id WHERE {" AND ".join(where)} ORDER BY {order} LIMIT ? OFFSET ? """ effective_offset = 0 if cursor else offset rows = cur.execute(sql, params + [limit, effective_offset]).fetchall() # Skip COUNT for cursor pages, and also for the rating sorts โ€” # top_rated/top_hated need to scan every row in the date range # (or whole table) to evaluate the color expression, which can # take 5+ s on cold pages. The user gets the visible page in # ~200 ms; an exact result count isn't worth the wait. UI shows # "โ€”" when total is -1. if cursor or sort in ("top_rated", "top_hated"): total = -1 else: total = cur.execute( f"""SELECT COUNT(*) FROM ( SELECT 1 FROM posts p JOIN threads t ON t.id=p.thread_id WHERE {' AND '.join(where)} LIMIT 10001 )""", params, ).fetchone()[0] result_dicts = [dict(r) for r in rows] # Quote-only detection + snippet rebuild: for results that have baked # HTML, strip the <blockquote> reply blocks to isolate the post's own # body. If any search term appears there, the match is "in body" and # the snippet is rebuilt as a window around that term. Otherwise the # match was purely on quoted text โ€” the snippet shows the start of # the actual reply (not the quote header) and the quote-only flag is # set. For unbaked posts we fall back to a heuristic plaintext strip # that removes 'ื ื›ืชื‘ ืข"ื™โ€ฆ' / 'ืฆื™ื˜ื•ื˜ ืฉืœโ€ฆ' header chunks, so the snippet # at least isn't the quote-chain metadata. if q: terms = _query_terms(q) for d in result_dicts: html = d.pop("_content_html", None) or "" d.pop("_file_path", None) if not terms: d["match_in_body"] = None continue if html: body = _strip_quotes_from_html(html) if not body.strip(): d["match_in_body"] = False continue d["match_in_body"] = any( _term_present_in_body(body.lower(), t) for t in terms ) snippet = _build_snippet(body, terms) if snippet: d["snippet"] = snippet else: # Unbaked: best-effort header strip on the substr-based # content snippet. We can't reliably tell quote vs body # from plain text, so match_in_body stays unknown. d["match_in_body"] = None raw = d.get("snippet") or "" if raw: cleaned = _strip_quote_headers_text(raw).strip() if cleaned: d["snippet"] = _build_snippet(cleaned, terms) else: # No search term โ€” still rebuild snippets from the post body when # we have baked HTML, so author-filter / sort-only views don't # show "ื ื›ืชื‘ ืข"ื™ X ื‘ืชืืจื™ืšโ€ฆ" quote headers as the snippet. With no # query there's nothing to highlight or center on; we just take # the start of the non-quoted body. for d in result_dicts: html = d.pop("_content_html", None) or "" d.pop("_file_path", None) if html: body = _strip_quotes_from_html(html).strip() if body: d["snippet"] = _build_snippet(body, terms=[]) else: raw = d.get("snippet") or "" if raw: cleaned = _strip_quote_headers_text(raw).strip() if cleaned: d["snippet"] = _build_snippet(cleaned, terms=[]) # Cursor advances by `limit` natural rows per page, NOT by the full # over-fetched window. Otherwise pages 2+ would skip rows the user # never saw โ€” and short result sets (total < over-fetch) would have # an "empty page 2" because page 1's cursor jumped past the end. The # over-fetch gives the tier sort a wider candidate pool; pagination # still walks the natural-order match set in `limit`-sized strides. next_cursor = prev_cursor = None if result_dicts and sort in ("newest", "oldest"): first = result_dicts[0] cursor_row = result_dicts[min(limit, len(result_dicts)) - 1] prev_cursor = f"{first.get('created_at') or ''}|{first.get('post_id') or first.get('id') or 0}" next_cursor = f"{cursor_row.get('created_at') or ''}|{cursor_row.get('post_id') or cursor_row.get('id') or 0}" # Tier sort: confirmed quote-only (false) sinks to the bottom of the # over-fetch window; everything else โ€” confirmed body match AND # unknown/unbaked โ€” stays in the SQL's natural sort order. This # preserves "newest = newest" semantics while still pushing posts # we've *proven* are quote-only matches to the bottom. if q: result_dicts.sort(key=lambda d: 1 if d.get("match_in_body") is False else 0) result_dicts = result_dicts[:limit] return { "scope": "posts", "total": total, "limit": limit, "offset": offset, "next_cursor": next_cursor, "prev_cursor": prev_cursor, "results": result_dicts, } finally: conn.close() @app.get("/api/find_post_by_quote") def find_post_by_quote(nick: str = Query(...), time: str = Query(...)): """Resolve a quoted-post reference (nick + timestamp from a quote header) to a concrete post id, so the UI can jump to the quoted message.""" # The quote header timestamp uses local time without a TZ ('2005-01-08 14:50:34'), # while we stored ISO with +03:00 offset. Match on the YYYY-MM-DDTHH:MM:SS prefix. iso_prefix = time.replace(" ", "T") conn = db() try: cur = conn.cursor() row = cur.execute( """ SELECT p.id AS post_id, p.thread_id, p.idx, u.nick FROM posts p JOIN users u ON u.id = p.author_id WHERE u.nick = ? AND p.created_at LIKE ? || '%' LIMIT 1 """, (nick, iso_prefix), ).fetchone() if not row: return {"found": False} return {"found": True, **dict(row)} finally: conn.close() @app.get("/api/post/{post_id}") def get_post(post_id: int, bare: bool = Query(False, description="Skip rich-HTML parsing (faster for list views)")): conn = db() try: cur = conn.cursor() row = cur.execute( """ SELECT p.id, p.idx, p.created_at, p.content, p.content_html, p.thread_id, p.color AS post_color, p.dsize AS post_dsize, p.rank_desc, p.rank_color, p.rank_dsize, p.author_id, u.nick AS author_nick, u.location AS author_location, u.messagecount AS author_messagecount, t.name AS thread_name, t.forum_id, t.archive, t.file_path, f.name AS forum_name, t.post_count AS thread_post_count FROM posts p LEFT JOIN users u ON u.id = p.author_id LEFT JOIN threads t ON t.id = p.thread_id LEFT JOIN forums f ON f.id = t.forum_id WHERE p.id = ? """, (post_id,), ).fetchone() if not row: raise HTTPException(status_code=404, detail="post not found") d = dict(row) file_path = d.pop("file_path") # Prefer baked content_html. If absent and caller wants rich HTML, # predict which sibling page file contains this post from its idx # (15 posts/page) and parse only that file. if bare: d["content_html"] = d.get("content_html") or "" elif d.get("content_html"): pass # already baked else: html = "" idx = d.get("idx") siblings = _sibling_page_files(file_path) if idx is not None and siblings: page_n = (idx - 1) // 15 wanted = None for s in siblings: if page_n == 0: if "&page=" not in s: wanted = s; break else: if f"&page={page_n}" in s: wanted = s; break if wanted: html = _post_html(wanted, post_id) if not html: for fp in siblings: html = _post_html(fp, post_id) if html: break d["content_html"] = html return d finally: conn.close() @app.get("/api/thread/{thread_id}") def get_thread( thread_id: int, highlight_post: Optional[int] = None, page: Optional[int] = Query(None, ge=0, description="0-based page index"), page_size: int = Query(20, ge=1, le=100), bare: bool = Query(False, description="Skip post fetching โ€” return only thread metadata"), ): """Thread fetch. When `page` is supplied, returns just that page of posts plus `total_posts`. Without it returns the whole thread (legacy / 'full' view mode). Performance: prefers posts.content_html (baked) when available; only falls back to on-the-fly HTML file parsing for the (possibly-empty) set of posts that haven't been baked yet.""" conn = db() try: cur = conn.cursor() thread = cur.execute( """ SELECT t.id, t.name, t.forum_id, t.archive, t.file_path, t.post_count AS total_posts, f.name AS forum_name FROM threads t LEFT JOIN forums f ON f.id = t.forum_id WHERE t.id = ? """, (thread_id,), ).fetchone() if not thread: raise HTTPException(status_code=404, detail="thread not found") thread_d = dict(thread) file_path = thread_d.pop("file_path") total_posts = thread_d.get("total_posts") or 0 if bare: return {"thread": thread_d, "posts": [], "page": None, "page_size": 0, "highlight_post": None} # Build query: full thread (no page) or one page only sql = """ SELECT p.id, p.idx, p.created_at, p.content, p.content_html, p.color AS post_color, p.dsize AS post_dsize, p.rank_desc, p.rank_color, p.rank_dsize, p.author_id, u.nick AS author_nick, u.location AS author_location, u.messagecount AS author_messagecount FROM posts p LEFT JOIN users u ON u.id = p.author_id WHERE p.thread_id = ? ORDER BY p.idx, p.id """ params: list = [thread_id] if page is not None: sql += " LIMIT ? OFFSET ?" params += [page_size, page * page_size] posts = cur.execute(sql, params).fetchall() post_list = [dict(p) for p in posts] # Fall back to file-parse only for posts whose content_html wasn't # baked. Be selective about WHICH sibling files we open โ€” only the # ones whose post indexes overlap missing posts (forum paginates at # 15 posts/page, so each file covers idx range [15*N+1, 15*N+15]). missing = [p for p in post_list if not p.get("content_html")] if missing: siblings = _sibling_page_files(file_path) wanted_pages = set() for p in missing: ix = p.get("idx") or 1 wanted_pages.add((ix - 1) // 15) def page_n_of(path): m = re.search(r"&page=(\d+)", path) return int(m.group(1)) if m else 0 relevant = [s for s in siblings if page_n_of(s) in wanted_pages] rich = {} for fp in (relevant or siblings): rich.update(_parse_thread_html(fp)) for p in missing: p["content_html"] = rich.get(p["id"], "") return { "thread": thread_d, "posts": post_list, "page": page, "page_size": page_size, "highlight_post": highlight_post, } finally: conn.close() @app.get("/api/forums") def list_forums(): conn = db() try: cur = conn.cursor() rows = cur.execute( """ SELECT f.id, f.name, COUNT(t.id) AS thread_count FROM forums f LEFT JOIN threads t ON t.forum_id = f.id GROUP BY f.id ORDER BY thread_count DESC """ ).fetchall() return {"forums": [dict(r) for r in rows]} finally: conn.close() @app.get("/api/discovery/random_thread") def random_thread(min_posts: int = Query(3, ge=1)): """Pick a random thread with at least min_posts posts.""" conn = db() try: cur = conn.cursor() # Fast random: pick a random rowid offset then scan forward. # Repeat up to 5x if the random pick lands on a tiny thread. for _ in range(5): row = cur.execute( """ SELECT t.id, t.name, t.forum_id, t.post_count, COALESCE(f.name, 'ืคื•ืจื•ื ' || t.forum_id) AS forum_name FROM threads t LEFT JOIN forums f ON f.id = t.forum_id WHERE t.rowid >= (ABS(RANDOM()) % (SELECT MAX(rowid) FROM threads)) AND t.post_count >= ? ORDER BY t.rowid LIMIT 1 """, (min_posts,), ).fetchone() if row: return dict(row) raise HTTPException(status_code=503, detail="couldn't find a random thread") finally: conn.close() @app.get("/api/discovery/top_users") def top_users(by: str = Query("messages", pattern="^(messages|threads_started)$"), limit: int = Query(50, ge=1, le=200)): """Leaderboard of users โ€” by total messages, or by threads they opened.""" conn = db() try: cur = conn.cursor() if by == "messages": rows = cur.execute( """ SELECT id, nick, location, messagecount AS metric FROM users WHERE messagecount IS NOT NULL AND nick IS NOT NULL ORDER BY messagecount DESC LIMIT ? """, (limit,), ).fetchall() else: # threads_started rows = cur.execute( """ SELECT u.id, u.nick, u.location, COUNT(*) AS metric FROM threads t JOIN users u ON u.id = t.first_author_id WHERE u.nick IS NOT NULL GROUP BY u.id ORDER BY metric DESC LIMIT ? """, (limit,), ).fetchall() return {"by": by, "results": [dict(r) for r in rows]} finally: conn.close() @app.get("/api/discovery/hot_threads") def hot_threads(limit: int = Query(50, ge=1, le=200), year: Optional[int] = None): """Threads with the most replies. Optional ?year=YYYY narrows to that year.""" conn = db() try: cur = conn.cursor() where = ["t.post_count >= 10"] params: list = [] if year is not None: where.append("t.first_post_at >= ? AND t.first_post_at < ?") params.append(f"{year}-01-01") params.append(f"{year+1}-01-01") sql = f""" SELECT t.id, t.name, t.forum_id, t.post_count, t.first_post_at, t.last_post_at, COALESCE(f.name, 'ืคื•ืจื•ื ' || t.forum_id) AS forum_name, u.nick AS first_author_nick FROM threads t LEFT JOIN forums f ON f.id = t.forum_id LEFT JOIN users u ON u.id = t.first_author_id WHERE {' AND '.join(where)} ORDER BY t.post_count DESC LIMIT ? """ rows = cur.execute(sql, params + [limit]).fetchall() return {"results": [dict(r) for r in rows]} finally: conn.close() @app.get("/api/stats") def stats(): conn = db() try: cur = conn.cursor() def one(sql): return cur.execute(sql).fetchone()[0] return { "threads": one("SELECT COUNT(*) FROM threads"), "posts": one("SELECT COUNT(*) FROM posts"), "users": one("SELECT COUNT(*) FROM users"), "forums": one("SELECT COUNT(*) FROM forums"), "date_min": one("SELECT MIN(created_at) FROM posts WHERE created_at IS NOT NULL"), "date_max": one("SELECT MAX(created_at) FROM posts WHERE created_at IS NOT NULL"), } finally: conn.close() @app.get("/api/user/{user_id}") def get_user_profile(user_id: int): """Profile view: header stats (post count, thread count, date range, latest known rank, avatar URL) + top-5 forums by post count.""" conn = db() try: cur = conn.cursor() user = cur.execute( "SELECT id, nick, location, messagecount FROM users WHERE id = ?", (user_id,), ).fetchone() if not user: raise HTTPException(status_code=404, detail="user not found") stats = cur.execute( """ SELECT COUNT(*) AS post_count, COUNT(DISTINCT thread_id) AS thread_count, MIN(created_at) AS first_post, MAX(created_at) AS last_post FROM posts WHERE author_id = ? """, (user_id,), ).fetchone() top_forums = cur.execute( """ SELECT f.id, COALESCE(f.name, 'ืคื•ืจื•ื ' || f.id) AS name, COUNT(*) AS posts FROM posts p JOIN threads t ON t.id = p.thread_id LEFT JOIN forums f ON f.id = t.forum_id WHERE p.author_id = ? GROUP BY f.id ORDER BY posts DESC LIMIT 5 """, (user_id,), ).fetchall() latest_rank = cur.execute( """ SELECT rank_desc, rank_color, rank_dsize FROM posts WHERE author_id = ? AND (rank_desc IS NOT NULL OR rank_dsize IS NOT NULL) ORDER BY created_at DESC NULLS LAST, id DESC LIMIT 1 """, (user_id,), ).fetchone() # Avatar existence โ€” cheap filesystem stat avatar_exists = (AVATAR_DIR / f"user{user_id}.jpg").exists() return { "user": dict(user), "stats": dict(stats), "top_forums": [dict(r) for r in top_forums], "latest_rank": dict(latest_rank) if latest_rank else None, "avatar_exists": avatar_exists, } finally: conn.close() @app.get("/api/users/search") def user_search(q: str = Query(..., min_length=1), limit: int = Query(10, ge=1, le=50)): conn = db() try: cur = conn.cursor() rows = cur.execute( """ SELECT id, nick, location, messagecount FROM users WHERE nick LIKE ? ORDER BY (messagecount IS NULL), messagecount DESC, id LIMIT ? """, (f"%{q}%", limit), ).fetchall() return {"users": [dict(r) for r in rows]} finally: conn.close() def _og_meta(props: dict[str, str]) -> str: """Render a dict of OG/Twitter meta tags as an HTML fragment.""" out: list[str] = [] for k, v in props.items(): if not v: continue # property vs name attribute: og:* uses property, twitter:* uses name attr = "property" if k.startswith("og:") else "name" out.append( f'<meta {attr}="{_html_escape(k)}" content="{_html_escape(str(v))}">' ) return "\n ".join(out) def _html_escape(s: str) -> str: return ( s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") .replace('"', "&quot;").replace("'", "&#39;") ) def _truncate(text: str, n: int = 200) -> str: text = re.sub(r"\s+", " ", (text or "")).strip() if len(text) <= n: return text return text[: n - 1].rstrip() + "โ€ฆ" def _og_for_post(conn, post_id: int) -> dict[str, str]: cur = conn.cursor() row = cur.execute( """ SELECT p.id, p.content, p.content_html, p.created_at, t.name AS thread_name, f.name AS forum_name, u.nick AS author_nick FROM posts p JOIN threads t ON t.id = p.thread_id LEFT JOIN forums f ON f.id = t.forum_id LEFT JOIN users u ON u.id = p.author_id WHERE p.id = ? """, (post_id,), ).fetchone() if not row: return {} d = dict(row) nick = d.get("author_nick") or "ืื ื•ื ื™ืžื™" thread = d.get("thread_name") or f"ื“ื™ื•ืŸ" forum = d.get("forum_name") or "" # Prefer stripped body from baked HTML; fall back to plain text. body_text = "" if d.get("content_html"): body_text = _strip_quotes_from_html(d["content_html"]).strip() if not body_text: body_text = _strip_quote_headers_text(d.get("content") or "").strip() return { "title": f"{nick}: {thread}", "description": _truncate(body_text, 200) or f"ื”ื•ื“ืขื” ืžืืช {nick} ื‘ื“ื™ื•ืŸ \"{thread}\"" + (f" ยท {forum}" if forum else ""), "type": "article", } def _og_for_thread(conn, thread_id: int) -> dict[str, str]: cur = conn.cursor() row = cur.execute( """ SELECT t.id, t.name AS thread_name, t.post_count, f.name AS forum_name, u.nick AS first_author_nick, (SELECT substr(p.content, 1, 400) FROM posts p WHERE p.thread_id = t.id ORDER BY p.idx LIMIT 1) AS first_excerpt FROM threads t LEFT JOIN forums f ON f.id = t.forum_id LEFT JOIN users u ON u.id = t.first_author_id WHERE t.id = ? """, (thread_id,), ).fetchone() if not row: return {} d = dict(row) name = d.get("thread_name") or f"ื“ื™ื•ืŸ {thread_id}" forum = d.get("forum_name") or "" nick = d.get("first_author_nick") posts = d.get("post_count") or 0 excerpt = _truncate(_strip_quote_headers_text(d.get("first_excerpt") or ""), 200) bits = [] if forum: bits.append(forum) if posts: bits.append(f"{posts:,} ื”ื•ื“ืขื•ืช".replace(",", ",")) if nick: bits.append(f"ืคืชื—: {nick}") subtitle = " ยท ".join(bits) return { "title": name, "description": excerpt or subtitle or f"ื“ื™ื•ืŸ ื‘ืืจื›ื™ื•ืŸ gamer.co.il", "type": "article", } def _build_og_block(request: Request) -> str: """Return an HTML fragment of OG/Twitter meta tags appropriate for the URL the user landed on. Crawlers like Slack/Twitter/Discord fetch the page once and read these tags to render a rich link card.""" qp = request.query_params url = str(request.url) # Sensible site-wide defaults. info = { "title": "Gamer Forums Archive", "description": ( "ืืจื›ื™ื•ืŸ ืคื•ืจื•ืžื™ gamer.co.il โ€” ื—ื™ืคื•ืฉ ืขืœ ืคื ื™ 10 ืžื™ืœื™ื•ืŸ ื”ื•ื“ืขื•ืช " "ื‘-546 ืืœืฃ ื“ื™ื•ื ื™ื (2004โ€“2014)." ), "type": "website", } # Per-item overrides. open_param = qp.get("open", "") try: if open_param.startswith("post:"): conn = db() try: info.update({k: v for k, v in _og_for_post(conn, int(open_param.split(":", 1)[1])).items() if v}) finally: conn.close() elif open_param.startswith("thread:"): conn = db() try: info.update({k: v for k, v in _og_for_thread(conn, int(open_param.split(":", 1)[1])).items() if v}) finally: conn.close() elif qp.get("q"): info["title"] = f'ื—ื™ืคื•ืฉ: "{qp.get("q")}" โ€” Gamer Forums Archive' except Exception: # Never let OG generation 500 the page. Defaults are good enough. pass og = { "og:site_name": "Gamer Forums Archive", "og:title": info["title"], "og:description": info["description"], "og:type": info["type"], "og:url": url, "og:image": str(request.base_url).rstrip("/") + "/static/logo.png", "og:image:width": "500", "og:image:height": "143", "og:locale": "he_IL", "twitter:card": "summary_large_image", "twitter:title": info["title"], "twitter:description": info["description"], "twitter:image": str(request.base_url).rstrip("/") + "/static/logo.png", } return _og_meta(og) @app.get("/") def root(request: Request): index = STATIC_DIR / "index.html" if not index.exists(): return JSONResponse({"error": "static/index.html not built yet"}, status_code=503) try: html = index.read_text(encoding="utf-8") except OSError: return FileResponse(index) og_block = _build_og_block(request) # Replace the placeholder if present; otherwise fall through to the # original file (covers both the templated case and any future direct # FileResponse fallback). if "<!--OG_TAGS-->" in html: html = html.replace("<!--OG_TAGS-->", og_block, 1) return HTMLResponse(html) if STATIC_DIR.exists(): app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") if AVATAR_DIR.exists(): app.mount("/avatars", StaticFiles(directory=AVATAR_DIR), name="avatars") if EMOJI_DIR.exists(): app.mount("/forum_emojis", StaticFiles(directory=EMOJI_DIR), name="forum_emojis")
"""FastAPI search server for the gamer2 archive.
Run:
uvicorn search.server:app --reload --port 8000
Endpoints:
GET / โ†’ single-page UI (static/index.html)
GET /api/search โ†’ FTS5 search with filters & snippets
GET /api/thread/{thread_id} โ†’ full thread (all posts in order)
GET /api/forums โ†’ list of forums
GET /api/stats โ†’ DB stats
"""
from __future__ import annotations
import os
import sqlite3
from pathlib import Path
from typing import Optional
import re
from functools import lru_cache
from bs4 import BeautifulSoup
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
from slowapi.util import get_remote_address
BASE_DIR = Path(__file__).resolve().parent
DB_PATH = Path(os.environ.get("GAMER_DB", BASE_DIR / "posts.db"))
STATIC_DIR = BASE_DIR / "static"
AVATAR_DIR = Path(
os.environ.get(
"GAMER_AVATARS",
BASE_DIR.parent / "gamer2" / "static" / "user_avatar",
)
)
EMOJI_DIR = Path(
os.environ.get(
"GAMER_EMOJIS",
BASE_DIR.parent / "gamer2" / "static" / "gamer" / "forum_images",
)
)
def db():
"""Open a fresh read-only connection per request (sqlite handles concurrency fine).
immutable=1 (not mode=ro) โ€” the DB was last written by bake_rich_html.py
in WAL mode, which leaves it expecting to lock -shm/-wal files even on
a "read-only" open. In the deployed Docker image posts.db lives on a
user-non-writable mount, so any lock attempt errors with "attempt to
write a readonly database". immutable=1 tells SQLite the file will not
change and to skip locking entirely โ€” perfect for our use case where
the DB is baked once at image-build time and never modified at runtime."""
uri = f"file:{DB_PATH}?immutable=1"
conn = sqlite3.connect(uri, uri=True, check_same_thread=False)
conn.row_factory = sqlite3.Row
# Best-effort perf PRAGMAs. cache_size and temp_store both attempt a
# schema write in some SQLite builds, which fails when the DB file is
# not user-writable (e.g. in the deployed Docker image where posts.db
# is owned by root and we run as an unprivileged user). mmap_size is
# the most important one โ€” it lets SQLite map the DB into the address
# space and read pages without going through the page cache.
for pragma in (
"PRAGMA mmap_size = 1073741824",
"PRAGMA cache_size = -262144",
"PRAGMA temp_store = MEMORY",
):
try:
conn.execute(pragma)
except sqlite3.OperationalError:
pass
return conn
_HEBREW_PREFIXES = ("ื”", "ื‘", "ื•", "ืœ", "ืž", "ืฉ", "ื›")
_HEBREW_LETTER_RE = re.compile(r"[ึ-ืฟ]")
# Hebrew stopwords โ€” short, ultra-common words whose postings lists are
# huge (millions of hits each). When they appear alongside other tokens
# we drop them from the FTS query so the rare tokens dominate the AND
# intersection; without this, a query like `ืื ื™ ืงื•ืคืฅ ื‘ื—ื“ืจ` had to scan
# 100k+ postings just for "ืื ื™". Users who need the literal word can
# wrap it in "double quotes" to bypass this filter.
_HEBREW_STOPWORDS = frozenset({
# personal pronouns
"ืื ื™", "ืืชื”", "ืืช", "ื”ื•ื", "ื”ื™ื", "ืื ื—ื ื•", "ืืชื", "ืืชืŸ", "ื”ื", "ื”ืŸ",
# demonstratives / common particles
"ื–ื”", "ื–ืืช", "ืืœื”", "ืืœื•", "ื›ืš", "ื›ื›ื”", "ืฉื", "ืคื”", "ื›ืืŸ",
# prepositions / conjunctions / fillers
"ืฉืœ", "ืขืœ", "ืขื", "ืืœ", "ื›ื™", "ืื", "ืื–", "ื’ื", "ืจืง", "ื›ืŸ", "ืœื",
"ืื‘ืœ", "ืื•", "ื›ืœ", "ื›ืžื•", "ื™ืฉ", "ืื™ืŸ", "ื”ื™ื”", "ื”ื™ื•", "ืื—ืจ", "ืœืคื ื™",
"ืื—ืจื™", "ื‘ื™ืŸ", "ืžื”", "ืžื™", "ืื™ืš", "ืœืžื”", "ืœื™", "ืœื•", "ืœื”", "ืœื ื•", "ืœื›ื",
})