#!/usr/bin/env python3 """Collect public Google Play app metadata for supplied IDs; no APK downloads. The HTML parser reads embedded JSON without executing JavaScript. Positional fields were checked on October 3, 2026; missing fields are exposed as warnings. Screenshot gallery positions are retained even when their URLs repeat. """ from __future__ import annotations import argparse from datetime import datetime, timezone import html as html_module from html.parser import HTMLParser import json from pathlib import Path import re import time from typing import Any from urllib.parse import parse_qs, unquote, urlsplit, urlunsplit import requests PARSER_VERSION = "1.1.0" _PACKAGE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+$") _CALLBACK = re.compile(r"\bAF_initDataCallback\s*\(\s*\{") _IMAGE_HOSTS = {"play-lh.googleusercontent.com", "lh3.googleusercontent.com"} _KNOWN_FORM_FACTORS = {2: "phone", 3: "tablet", 4: "wear", 5: "desktop", 7: "car"} def _path(value: Any, *parts: Any) -> Any: for part in parts: try: value = value[part] except (IndexError, KeyError, TypeError): return None return value def _quoted_end(text: str, start: int) -> int: quote = text[start] cursor = start + 1 while cursor < len(text): if text[cursor] == "\\": cursor += 2 elif text[cursor] == quote: return cursor + 1 else: cursor += 1 raise ValueError("Unterminated quoted string") def _callback_fields(text: str, start: int) -> dict[str, int]: """Locate top-level literal property values, ignoring nested/quoted text.""" fields: dict[str, int] = {} depth = 1 cursor = start while cursor < len(text) and depth: char = text[cursor] if char in "\"'`": end = _quoted_end(text, cursor) if depth == 1: after = end while after < len(text) and text[after].isspace(): after += 1 if after < len(text) and text[after] == ":": fields[text[cursor + 1:end - 1]] = after + 1 cursor = end continue if char in "[{(": depth += 1 elif char in "]})": depth -= 1 elif depth == 1 and (char.isalpha() or char == "_"): end = cursor + 1 while end < len(text) and (text[end].isalnum() or text[end] == "_"): end += 1 after = end while after < len(text) and text[after].isspace(): after += 1 if after < len(text) and text[after] == ":": fields[text[cursor:end]] = after + 1 cursor = end continue cursor += 1 return fields def extract_initial_data(page_html: str) -> tuple[dict[str, Any], list[str]]: """Decode AF callback data as JSON; never evaluate JS or arbitrary literals.""" datasets: dict[str, Any] = {} warnings: list[str] = [] decoder = json.JSONDecoder() for callback in _CALLBACK.finditer(page_html): try: fields = _callback_fields(page_html, callback.end()) key_start = fields.get("key") data_start = fields.get("data") if key_start is None or data_start is None: warnings.append("callback_missing_key_or_data") continue key_literal = page_html[key_start:].lstrip() key_match = re.match(r"['\"](ds:\d+)['\"]", key_literal) if not key_match: warnings.append("callback_key_not_supported") continue key = key_match[1] data, end = decoder.raw_decode(page_html[data_start:].lstrip()) remainder = page_html[data_start:].lstrip()[end:].lstrip() if not remainder.startswith((",", "}")): raise ValueError("Data field contains an expression after JSON") if key in datasets: warnings.append(f"duplicate_dataset:{key}") datasets[key] = data except (ValueError, RecursionError) as error: warnings.append(f"callback_decode_failed:{type(error).__name__}") if not datasets: warnings.append("no_initial_data") return datasets, list(dict.fromkeys(warnings)) class _PageMarkup(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.links: list[str] = [] self.screenshots: list[dict[str, str]] = [] self.form_factors: list[dict[str, Any]] = [] self.canonical_url: str | None = None self.json_ld: list[Any] = [] self._ld_parts: list[str] | None = None def handle_starttag(self, tag: str, attributes: list[tuple[str, str | None]]) -> None: attrs = {key: value for key, value in attributes if value is not None} if tag == "a" and attrs.get("href"): self.links.append(attrs["href"]) if tag == "link" and attrs.get("rel") == "canonical": self.canonical_url = attrs.get("href") if tag == "img" and attrs.get("alt", "").lower() == "screenshot image": self.screenshots.append(attrs) factor = re.fullmatch(r"formFactor_(\d+)", attrs.get("id", "")) if factor: code = int(factor[1]) self.form_factors.append({"code": code, "name": _KNOWN_FORM_FACTORS.get(code, "unknown"), "label": attrs.get("aria-label"), "source": "html_review_filter"}) if tag == "script" and attrs.get("type") == "application/ld+json": self._ld_parts = [] def handle_data(self, data: str) -> None: if self._ld_parts is not None: self._ld_parts.append(data) def handle_endtag(self, tag: str) -> None: if tag == "script" and self._ld_parts is not None: try: self.json_ld.append(json.loads("".join(self._ld_parts))) except ValueError: pass self._ld_parts = None def full_size_image_url(url: str) -> str: """Request Google's largest available asset; this does not upscale pixels.""" parts = urlsplit(html_module.unescape(url)) host = (parts.hostname or "").lower() if host not in _IMAGE_HOSTS and not re.fullmatch(r"lh[3-6]\.ggpht\.com", host): return url image_path = unquote(parts.path) image_path = re.sub(r"=(?:[swh]\d+|[A-Za-z]+-)[A-Za-z0-9_-]*$", "", image_path) return urlunsplit((parts.scheme, parts.netloc, image_path + "=s0", parts.query, "")) def _app_id_from_url(url: str | None) -> str | None: if not url: return None decoded = html_module.unescape(url) parts = urlsplit(decoded) if parts.path != "/store/apps/details": return None value = parse_qs(parts.query).get("id", [None])[0] return value if isinstance(value, str) and _PACKAGE.fullmatch(value) else None def _strings(value: Any): if isinstance(value, str): yield value elif isinstance(value, list): for item in value: yield from _strings(item) elif isinstance(value, dict): for item in value.values(): yield from _strings(item) def discover_app_ids(page_html: str) -> list[str]: """Discover linked package IDs on listings, search results, or collections.""" markup = _PageMarkup() markup.feed(page_html) datasets, _ = extract_initial_data(page_html) values = markup.links + list(_strings(datasets)) ids = {app_id for value in values if (app_id := _app_id_from_url(value))} return sorted(ids) def _plain_text(value: str | None) -> str | None: if not isinstance(value, str): return None value = re.sub(r"", "\n", value, flags=re.I) value = re.sub(r"", "\n", value, flags=re.I) return html_module.unescape(re.sub(r"<[^>]+>", "", value)).strip() def _positive_integer(value: Any) -> int | None: return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None def parse_play_html(page_html: str, app_id: str | None = None, source_url: str | None = None) -> dict[str, Any]: """Return metadata and a full gallery with conservative device attribution. ``wear_support=confirmed`` means structured metadata and the rendered Watch review filter agree, not a guarantee that every Wear OS device can install it. Description mentions alone are candidates. A square screenshot is only a hint and never promotes the app or image to a confirmed Wear classification. In a confirmed Wear-only listing, gallery assets receive contextual Wear labels; their content can still be marketing art rather than pure UI. """ datasets, warnings = extract_initial_data(page_html) markup = _PageMarkup() markup.feed(page_html) details = _path(datasets, "ds:5", 1, 2) detail_key = "ds:5" if not isinstance(details, list) or not isinstance(_path(details, 77, 0), str): details = None for key, value in datasets.items(): possible = _path(value, 1, 2) possible_id = _path(possible, 77, 0) if isinstance(possible_id, str) and _PACKAGE.fullmatch(possible_id): if app_id is None or possible_id == app_id: details, detail_key = possible, key warnings.append("detail_dataset_key_changed") break observed_id = _path(details, 77, 0) or _app_id_from_url(markup.canonical_url) requested_id = app_id or _app_id_from_url(source_url) identity_matches = (observed_id == requested_id) if observed_id and requested_id else None if identity_matches is False: warnings.append("requested_and_observed_app_ids_differ") selected_id = observed_id or requested_id title = _path(details, 0, 0) description_html = _path(details, 12, 0, 0, 1) or _path(details, 72, 0, 1) if not title: for value in markup.json_ld: if isinstance(value, dict) and value.get("@type") == "SoftwareApplication": title = value.get("name") description_html = description_html or value.get("description") break if not title: warnings.append("missing_app_title") if details is None: warnings.append("missing_structured_app_details") screenshots: list[dict[str, Any]] = [] gallery = _path(details, 78, 0) if isinstance(gallery, list): for index, entry in enumerate(gallery): url = _path(entry, 3, 2) if not isinstance(url, str) or not url.startswith("https://"): warnings.append(f"invalid_screenshot_record:{index}") continue height = _positive_integer(_path(entry, 2, 0)) width = _positive_integer(_path(entry, 2, 1)) square = bool(width and height and width == height) screenshots.append({ "index": index, "url": url, "download_url": full_size_image_url(url), "width": width, "height": height, "source_path": [detail_key, 1, 2, 78, 0, index], "form_factor": "unknown", "form_factor_evidence": [], "form_factor_hint": ("square_wear_candidate" if square else "phone_candidate" if width and height and height > width else "landscape_unknown" if width and height else "unknown"), "device_classification_status": "unverified", }) if not screenshots: for index, attrs in enumerate(markup.screenshots): url = attrs.get("src") or attrs.get("data-src") if not url or not url.startswith("https://"): continue screenshots.append({ "index": index, "url": url, "download_url": full_size_image_url(url), "width": None, "height": None, "source_path": ["html", "screenshot_image", index], "form_factor": "unknown", "form_factor_evidence": [], "form_factor_hint": "unknown", "device_classification_status": "unverified", }) if screenshots: warnings.append("screenshot_dom_fallback_dimensions_unknown") else: warnings.append("no_screenshots") gallery_entry_count = len(screenshots) unique_screenshots: dict[str, dict[str, Any]] = {} for screenshot in screenshots: existing = unique_screenshots.get(screenshot["url"]) if existing is None: screenshot["source_gallery_indices"] = [screenshot["index"]] screenshot["source_paths"] = [screenshot["source_path"]] screenshot["screenshot_content_status"] = "unverified" unique_screenshots[screenshot["url"]] = screenshot else: existing["source_gallery_indices"].append(screenshot["index"]) existing["source_paths"].append(screenshot["source_path"]) if (existing["width"], existing["height"]) != (screenshot["width"], screenshot["height"]): warnings.append(f"duplicate_screenshot_dimensions_differ:{screenshot['index']}") screenshots = list(unique_screenshots.values()) factor_codes = _path(details, 150, 0) form_factors = list(markup.form_factors) if isinstance(factor_codes, list): for code in factor_codes: if isinstance(code, int) and not any(x["code"] == code for x in form_factors): form_factors.append({"code": code, "name": _KNOWN_FORM_FACTORS.get(code, "unknown"), "label": None, "source": "structured_review_form_factors"}) wear_evidence: list[dict[str, Any]] = [] structured_watch = isinstance(factor_codes, list) and 4 in factor_codes labeled_watch = any(item["code"] == 4 and (item.get("label") or "").lower() == "watch" for item in markup.form_factors) for factor in form_factors: if factor["code"] == 4: wear_evidence.append({"type": "watch_review_form_factor", "strength": "listing_confirmed" if structured_watch and labeled_watch else "candidate", "value": factor, "structured_watch_code": structured_watch, "labeled_watch_control": labeled_watch, "limitation": "Does not establish device-level installability."}) description = _plain_text(description_html) for field_name, content in (("title", title), ("description", description)): if not isinstance(content, str): continue for match in re.finditer(r"\b(?:Wear\s*OS|Android\s+Wear)\b", content, re.I): wear_evidence.append({"type": "text_mention", "strength": "candidate", "field": field_name, "value": content[max(0, match.start() - 90):match.end() + 120]}) wear_support = "confirmed" if any(x["strength"] == "listing_confirmed" for x in wear_evidence) else ( "candidate" if wear_evidence else "unknown") if identity_matches is False: wear_support = "unknown" if (wear_support == "confirmed" and isinstance(factor_codes, list) and set(factor_codes) == {4} and {item["code"] for item in form_factors} == {4}): for screenshot in screenshots: screenshot["form_factor"] = "wear" screenshot["device_classification_status"] = "listing_context" screenshot["form_factor_evidence"] = [{ "type": "wear_only_listing", "supported_form_factor_codes": [4], "limitation": "Contextual listing attribution; image content and pure UI status are unverified.", }] developer_url = _path(details, 68, 1, 4, 2) developer_id = parse_qs(urlsplit(developer_url).query).get("id", [None])[0] if isinstance(developer_url, str) else None linked_ids = {value for item in markup.links + list(_strings(datasets)) if (value := _app_id_from_url(item))} linked_ids.discard(selected_id) return { "parser_version": PARSER_VERSION, "app_id": selected_id, "requested_app_id": requested_id, "observed_app_id": observed_id, "identity_matches": identity_matches, "title": title, "description": description, "summary": _plain_text(_path(details, 73, 0, 1)), "developer": _path(details, 68, 0), "developer_id": developer_id, "genre": _path(details, 79, 0, 0, 0), "genre_id": _path(details, 79, 0, 0, 2), "icon_url": _path(details, 95, 0, 3, 2), "header_image_url": _path(details, 96, 0, 3, 2), "source_url": source_url or markup.canonical_url, "screenshots": screenshots, "gallery_entry_count": gallery_entry_count, "unique_screenshot_count": len(screenshots), "form_factors": form_factors, "wear_support": wear_support, "wear_evidence": wear_evidence, "related_app_ids": sorted(linked_ids), "parse_warnings": list(dict.fromkeys(warnings)), } APP_FIELDS = frozenset({'app_id', 'store', 'title', 'description', 'source_url', 'metadata'}) GOOGLE_METADATA_FIELDS = frozenset({ 'summary', 'developer', 'developerId', 'developerInternalID', 'developerWebsite', 'genre', 'genreId', 'categories', 'price', 'currency', 'free', 'score', 'ratings', 'version', 'updated', 'androidVersion', 'androidVersionText', 'androidMaxVersion', 'screenshots', 'icon', 'headerImage', 'videoImage', 'permissions', 'datasafety', }) def read_jsonl(path): with Path(path).open(encoding="utf-8") as stream: for line in stream: if line.strip(): yield json.loads(line) def write_line(stream, value): stream.write(json.dumps(value, ensure_ascii=False, separators=(",", ":")) + "\n") def app_document(row): """View public root fields in the raw collector's names without mutating rows. Root values take precedence even when explicitly null. Missing values are not synthesized, and unwrapped raw collector documents remain supported. """ if 'metadata' not in row and 'app_id' not in row: return dict(row) metadata = row.get('metadata') document = dict(metadata) if isinstance(metadata, dict) else {} for public_key, source_key in (('app_id', 'appId'), ('title', 'title'), ('description', 'description'), ('source_url', 'url')): if public_key in row: document[source_key] = row[public_key] return document def clean_app(row): """Project Google Play app fields without changing the input record.""" result = {key: value for key, value in row.items() if key in APP_FIELDS} metadata = row.get("metadata") if isinstance(metadata, dict): result["metadata"] = {key: value for key, value in metadata.items() if key in GOOGLE_METADATA_FIELDS} return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--ids", type=Path, required=True, help="One package ID per line, or app JSONL.") parser.add_argument("--output", type=Path, required=True) parser.add_argument("--country", default="us") parser.add_argument("--language", default="en") parser.add_argument("--interval", type=float, default=1.0) parser.add_argument("--limit", type=int) args = parser.parse_args() if args.output.exists(): parser.error("Output already exists; choose a new snapshot path.") args.output.parent.mkdir(parents=True, exist_ok=True) session, seen = requests.Session(), set() session.headers["User-Agent"] = "Mozilla/5.0 PhoneWatchUI-research" with args.ids.open() as inputs, args.output.open("x", encoding="utf-8") as output: for line in inputs: text = line.strip() if not text: continue if text.startswith("{"): row = json.loads(text) app_id = row.get("app_id") or row.get("appId") else: app_id = text if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+", app_id or ""): raise ValueError("Invalid package ID in input") if app_id in seen: continue if args.limit is not None and len(seen) >= args.limit: break seen.add(app_id) url = "https://play.google.com/store/apps/details" params = {"id":app_id, "hl":args.language, "gl":args.country} source_url = requests.Request("GET", url, params=params).prepare().url record = dict(app_id=app_id, store="google_play", title=None, description=None, source_url=source_url, watch_selection=None, metadata={}, fetched_at=datetime.now(timezone.utc).isoformat()) try: response = session.get(url, params=params, timeout=(15, 60)) response.raise_for_status() metadata = parse_play_html(response.text, app_id, source_url) if not metadata.get("title") or metadata.get("identity_matches") is False: raise ValueError("Listing identity/title validation failed") record.update(title=metadata.get("title"), description=metadata.get("description"), metadata=metadata, download_status="downloaded", error=None) except (requests.RequestException, ValueError) as error: record.update(download_status="failed", error=type(error).__name__) write_line(output, record) output.flush() print(json.dumps({"app_id":app_id,"status":record["download_status"]}), flush=True) time.sleep(max(0, args.interval)) if __name__ == "__main__": main()