Files
romm/backend/handler/walkthrough/gamefaqs.py
Georges-Antoine Assi 3c95231294 feat: walkthrough documents with reading progress and GameFAQs import
Unify manuals and walkthroughs on one document model instead of a
separate walkthrough subsystem. Walkthroughs are RomFiles under a new
WALKTHROUGH category with an optional RomFileDocMeta provenance sidecar,
and reading progress is a per-user RomFileUser row keyed on rom_file_id
so the same mechanism covers manuals and walkthroughs.

Backend:
- models: RomFileCategory.WALKTHROUGH, DocSource, RomFileDocMeta,
  RomFileUser; migration 0110 (enum value + two tables, cross-DB)
- serve .txt/.html documents inline (HTML under a sandboxing CSP);
  add .txt to allowed manual files
- endpoints: walkthrough upload / GameFAQs fetch / delete, and per-user
  reading-progress GET (ROMS_READ) / PUT (ROMS_USER_WRITE, like notes, so a
  kiosk guest capped to the read scopes cannot write)
- last_page is range-checked, so an out-of-range value is a 400 rather than
  an integer column overflow
- the guide body is read under the size cap instead of being buffered in
  full and truncated afterwards
- GameFAQs import extracts text only (stored as .txt); no remote HTML is
  persisted or served. Host-allowlisted on top of the SSRF-safe client
- a Cloudflare bot challenge is detected and reported as "open it in your
  browser and upload the text" instead of an opaque 403
- reading-progress upsert retries as an update on a unique-constraint
  race, so concurrent saves for one user/file can't 500
- a GameFAQs guide is removed from disk again if indexing it fails,
  rather than being left unreferenced
- tests for CRUD, progress, the GameFAQs parser/URL validation, and
  hidden-rom masking on every walkthrough route

Frontend (v2):
- TextViewer (.txt/.html), useReadingProgress composable, WalkthroughSubtab
  (upload + add-from-GameFAQs-URL + delete + progress), wired into MediaTab
- ManualSubtab renders .txt manuals; walkthrough category surfaced in
  FilesTab; regenerated types; i18n keys across all locales
- a pending scroll position is committed before the viewer follows a new
  document, so switching files mid-debounce no longer drops it
- WalkthroughSubtab gates upload, the GameFAQs URL field, and delete on
  useCan("rom.edit"), as ManualSubtab already does

AI assistance: implemented with Claude Code (Opus 4.8). The data-model
design, backend, migration, tests, and v2 UI were AI-authored under human
direction. Alternative approach to #2892.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-25 19:40:20 -04:00

208 lines
6.9 KiB
Python

"""Fetch GameFAQs text guides into the walkthrough document model.
Design note: we extract plain text only and never store or serve remote HTML.
GameFAQs text guides live inside a `<pre>` (or a `#faqtext` container), so
pulling the text out sidesteps HTML sanitization entirely: nothing script
capable is ever persisted. The outbound request also rides the shared,
SSRF-protected httpx client, with an extra host allowlist below.
"""
from __future__ import annotations
from html.parser import HTMLParser
from typing import TypedDict
from urllib.parse import urlparse
import httpx
from utils.context import ctx_httpx_client
GAMEFAQS_HOSTS = frozenset(
{
"gamefaqs.gamespot.com",
"www.gamefaqs.com",
"gamefaqs.com",
}
)
# Cap the response we will read into memory (guides are text; 8 MiB is plenty).
MAX_GUIDE_BYTES = 8 * 1024 * 1024
_TITLE_SUFFIXES = (" - Guide and Walkthrough", " - FAQ", " - GameFAQs")
class ParsedGuide(TypedDict):
title: str | None
author: str | None
text: str
class GameFAQsFetchError(Exception):
"""Raised when a GameFAQs guide cannot be fetched or parsed."""
def validate_gamefaqs_url(url: str) -> str:
"""Return the URL if it is a well-formed https GameFAQs URL, else raise."""
parsed = urlparse(url)
if parsed.scheme != "https":
raise ValueError("Walkthrough URL must use https")
host = (parsed.hostname or "").lower()
if host not in GAMEFAQS_HOSTS:
raise ValueError(
"Only GameFAQs guide URLs are supported "
f"(allowed hosts: {', '.join(sorted(GAMEFAQS_HOSTS))})"
)
return url
class _GuideExtractor(HTMLParser):
"""Pull the guide title, author, and body text out of a GameFAQs page.
Body text is captured from any `<pre>` element or any element whose id or
class contains "faqtext". Meta tags supply the title/author when present.
"""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.title: str | None = None
self.author: str | None = None
self._meta_title: str | None = None
self._capture_depth = 0
self._in_title = False
self._title_buf: list[str] = []
self._body_buf: list[str] = []
@staticmethod
def _is_capture_tag(tag: str, attrs: dict[str, str]) -> bool:
if tag == "pre":
return True
ident = f"{attrs.get('id', '')} {attrs.get('class', '')}".lower()
return "faqtext" in ident
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
attr_map = {k: (v or "") for k, v in attrs}
if tag == "title":
self._in_title = True
elif tag == "meta":
name = attr_map.get("name", "").lower()
prop = attr_map.get("property", "").lower()
content = attr_map.get("content", "").strip()
if content and name == "author" and not self.author:
self.author = content[:512]
if content and prop == "og:title" and not self._meta_title:
self._meta_title = content
if self._capture_depth > 0:
self._capture_depth += 1
elif self._is_capture_tag(tag, attr_map):
self._capture_depth = 1
def handle_endtag(self, tag: str) -> None:
if tag == "title":
self._in_title = False
if self._capture_depth > 0:
self._capture_depth -= 1
def handle_data(self, data: str) -> None:
if self._in_title:
self._title_buf.append(data)
if self._capture_depth > 0:
self._body_buf.append(data)
def finalize(self) -> ParsedGuide:
raw_title = self._meta_title or "".join(self._title_buf).strip() or None
title = _clean_title(raw_title)
text = "".join(self._body_buf).strip()
return ParsedGuide(title=title, author=self.author, text=text)
def _clean_title(title: str | None) -> str | None:
if not title:
return None
cleaned = title.strip()
for suffix in _TITLE_SUFFIXES:
if cleaned.endswith(suffix):
cleaned = cleaned[: -len(suffix)].strip()
return cleaned[:512] or None
def parse_gamefaqs_guide(html: str) -> ParsedGuide:
"""Parse a GameFAQs guide HTML string into title/author/text.
Pure function (no I/O) so it can be unit-tested against saved fixtures.
"""
extractor = _GuideExtractor()
extractor.feed(html)
extractor.close()
return extractor.finalize()
def is_bot_challenge(response: httpx.Response) -> bool:
"""Whether the response is an anti-bot interstitial rather than the guide.
Cloudflare marks a served challenge with `Cf-Mitigated`; some edges only
identify themselves in `Server` alongside the refusal status.
"""
if response.status_code not in (403, 503):
return False
if "cf-mitigated" in response.headers:
return True
return "cloudflare" in response.headers.get("server", "").lower()
async def fetch_gamefaqs_guide(url: str) -> ParsedGuide:
"""Fetch and parse a GameFAQs guide. Raises GameFAQsFetchError on failure."""
validate_gamefaqs_url(url)
client = ctx_httpx_client.get()
request = client.build_request(
"GET",
url,
headers={
"User-Agent": "Mozilla/5.0 (compatible; RomM/1.0; +https://romm.app)",
"Accept": "text/html,application/xhtml+xml",
},
timeout=30.0,
)
try:
# Streamed so the size cap bounds what is read, rather than truncating a
# body already buffered in full.
response = await client.send(request, stream=True, follow_redirects=True)
except Exception as exc:
raise GameFAQsFetchError(f"Could not fetch guide: {exc}") from exc
try:
# A challenge page carries a 403 and challenge HTML, so it would
# otherwise surface as an opaque status error or an empty parse.
if is_bot_challenge(response):
raise GameFAQsFetchError(
"GameFAQs is blocking automated requests for this guide. Open "
"the guide in your browser, save it as a text file, and upload "
"it here instead."
)
chunks: list[bytes] = []
read = 0
try:
response.raise_for_status()
async for chunk in response.aiter_bytes():
chunks.append(chunk)
read += len(chunk)
if read >= MAX_GUIDE_BYTES:
break
except Exception as exc:
raise GameFAQsFetchError(f"Could not fetch guide: {exc}") from exc
finally:
await response.aclose()
content = b"".join(chunks)[:MAX_GUIDE_BYTES]
guide = parse_gamefaqs_guide(content.decode("utf-8", errors="replace"))
if not guide["text"]:
raise GameFAQsFetchError(
"No guide text found at that URL. It may be a formatted guide or "
"an unsupported page."
)
return guide