#!/usr/bin/env python3 """Extract markers from all Aion 2 maps and export to JSON. Discovers all available maps, fetches their marker data with anti-scraping token handling, de-poisons coordinates, and exports per-map JSON files. Usage: python extract_all_markers.py # Extract all maps python extract_all_markers.py --map verteron # Specific map only """ import argparse import json import os import sys import time import urllib.error import urllib.parse import urllib.request API_BASE = "https://interactivemap.app/aion2/maps/imapp" USER_AGENT = "Mozilla/5.0 (aion2-marker-extractor/2.0)" def http_get_json(url: str, retries: int = 4) -> object: """GET a JSON endpoint with retry logic.""" last_err = None for attempt in range(1, retries + 1): try: req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) with urllib.request.urlopen(req, timeout=30) as resp: text = resp.read().decode("utf-8") if text.lstrip()[:1] == "<": raise ValueError("HTML fallback received instead of JSON") return json.loads(text) except (urllib.error.URLError, ValueError, TimeoutError) as exc: last_err = exc if attempt < retries: time.sleep(1.5 * attempt) raise RuntimeError(f"GET {url} failed after {retries} attempts: {last_err}") def http_get_text(url: str) -> str: """GET a text endpoint.""" req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) with urllib.request.urlopen(req, timeout=30) as resp: return resp.read().decode("utf-8").strip() def fnv1a32(s: str) -> int: """FNV-1a 32-bit hash over UTF-8 bytes.""" h = 0x811C9DC5 for b in s.encode("utf-8"): h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF return h def js_mod(v: float, m: int) -> float: """JavaScript-style positive modulo.""" return ((v % m) + m) % m def discover_maps() -> list: """Discover all available maps from the API.""" print("Discovering available maps...") maps_data = http_get_json(f"{API_BASE}/api/getmaps") maps = [] zones = maps_data if isinstance(maps_data, list) else maps_data.get("groups", []) for zone in zones: zone_name = zone.get("name", "Unknown") for entry in zone.get("maps", []): maps.append({ "id": str(entry.get("id")), "slug": str(entry.get("slug")), "name": entry.get("name"), "zone": zone_name }) print(f"Found {len(maps)} maps") return maps def fetch_token() -> str: """Fetch anti-scraping token.""" token = http_get_text(f"{API_BASE}/api/mtoken/1?_={int(time.time() * 1000)}") if not token: raise RuntimeError("Empty anti-scraping token received") return token def fetch_map_markers(map_info: dict) -> tuple: """Fetch and de-poison markers for a single map. Returns (token, data, marker_count).""" slug = map_info["slug"] map_id = map_info["id"] print(f" Fetching markers for {map_info['name']} ({slug})...") for attempt in (1, 2): token = fetch_token() url = f"{API_BASE}/api/{map_id}/options.json?t=" + urllib.parse.quote(token) data = http_get_json(url) groups = data.get("groups") or [] n_markers = sum( len(c.get("data") or []) for g in groups for c in (g.get("categories") or []) ) if n_markers > 0: return token, data, n_markers print(f" Warning: attempt {attempt} returned no markers — retrying with fresh token", file=sys.stderr) raise RuntimeError(f"Map '{slug}' (id {map_id}) returned zero markers") def de_poison_and_flatten(token: str, data: dict) -> list: """Walk groups -> categories -> markers, undo coordinate offsets, flatten to records.""" markers = [] for group in data.get("groups") or []: g_id, g_name = group.get("id"), group.get("name") for cat in group.get("categories") or []: c_id, c_name = cat.get("id"), cat.get("name") for item in cat.get("data") or []: props = item.get("properties") or {} coords = item.get("coordinates") fixed = None if isinstance(coords, list) and len(coords) >= 2: mid = str(props["id"]) if props.get("id") is not None else "" ox = fnv1a32(token + mid + "x") % 4096 oy = fnv1a32(token + mid + "y") % 4096 fixed = [ js_mod(float(coords[0]) - ox, 4096), js_mod(float(coords[1]) - oy, 4096), ] rec = { "id": props.get("id"), "name": props.get("name"), "description": props.get("description"), "group_id": g_id, "group_name": g_name, "category_id": c_id, "category_name": c_name, "coordinates": fixed, "properties": props } markers.append(rec) return markers def extract_map_markers(map_info: dict, out_dir: str) -> None: """Extract and save markers for a single map.""" slug = map_info["slug"] try: token, data, n_markers = fetch_map_markers(map_info) print(f" De-poisoning {n_markers} coordinates...") markers = de_poison_and_flatten(token, data) export = { "source": f"https://interactivemap.app/aion2/maps/{slug}", "extracted_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "map": { "id": map_info["id"], "name": map_info["name"], "slug": slug, "zone": map_info.get("zone"), "last_update": data.get("last_update") }, "marker_count": len(markers), "markers": markers } out_path = os.path.join(out_dir, f"{slug}_markers.json") with open(out_path, "w", encoding="utf-8") as fh: json.dump(export, fh, ensure_ascii=False, indent=2) # Print category breakdown by_cat = {} for m in markers: key = f"{m['group_name']}/{m['category_name']}" by_cat[key] = by_cat.get(key, 0) + 1 print(f" Saved {len(markers)} markers to {out_path}") except Exception as e: print(f" Error extracting markers for {slug}: {e}", file=sys.stderr) def main(): parser = argparse.ArgumentParser(description="Extract markers from all Aion 2 maps") parser.add_argument("--map", type=str, default=None, help="Extract specific map by slug only") parser.add_argument("-o", "--out-dir", default="../data/markers", help="Output directory for marker JSON files") args = parser.parse_args() # Resolve output directory relative to script location script_dir = os.path.dirname(os.path.abspath(__file__)) out_dir = os.path.join(script_dir, args.out_dir) if not os.path.isabs(args.out_dir) else args.out_dir os.makedirs(out_dir, exist_ok=True) maps = discover_maps() if args.map: target = [m for m in maps if m["slug"] == args.map] if not target: print(f"Error: Map '{args.map}' not found. Available slugs:") for m in maps: print(f" {m['slug']}") sys.exit(1) maps = target t_start = time.time() for map_info in maps: extract_map_markers(map_info, out_dir) elapsed = time.time() - t_start print(f"\nAll marker extraction complete in {elapsed:.0f}s") print(f"Output directory: {out_dir}") if __name__ == "__main__": main()