#!/usr/bin/env python3 """Download all unique marker icon graphics from interactivemap.app. Scans all local marker JSON files to find unique icon image paths, then downloads each icon and saves it locally for the map viewer to use. Usage: python download_marker_icons.py # Download all icons python download_marker_icons.py -o ./icons # Custom output directory """ import argparse import json import os import sys import time import urllib.error import urllib.request from concurrent.futures import ThreadPoolExecutor, as_completed BASE_URL = "https://interactivemap.app" USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) aion2-icon-downloader/1.0" def collect_unique_icons(markers_dir): """Scan all marker JSON files and collect unique icon image paths.""" print(f"Scanning for icons in: {markers_dir}") if not os.path.exists(markers_dir): print(f"Error: Markers directory not found: {markers_dir}") return set() icons = set() json_files = [f for f in os.listdir(markers_dir) if f.endswith('_markers.json')] print(f"Found {len(json_files)} marker files") for filename in json_files: filepath = os.path.join(markers_dir, filename) try: with open(filepath, 'r', encoding='utf-8') as f: data = json.load(f) markers = data.get('markers', []) for marker in markers: props = marker.get('properties', {}) icon_image = props.get('icon_image') if icon_image: # Remove query string (version parameter) clean_path = icon_image.split('?')[0] icons.add(clean_path) except Exception as e: print(f" Warning: Failed to read {filename}: {e}") print(f"Found {len(icons)} unique icon paths") return icons def pick_one_path_per_filename(icon_paths): """Ordnet jedem Dateinamen genau einen Quellpfad zu. Die Icons werden nur unter ihrem Dateinamen gespeichert (der Viewer sucht sie genauso). Teilen sich mehrere Quellpfade einen Namen, wird nur einer geladen - sonst schreiben zwei Downloads gleichzeitig in dieselbe Datei und es ist Zufall, welches Bild uebrig bleibt. Beispiel: /admin/assets/icons/kibelisk.png (blauer Kisk) und /aion2/maps/admin/assets/icons/location/kibelisk.png (lila Kisk). Rueckgabe: (Dateiname -> geladener Pfad, Dateiname -> alle Pfade bei Kollisionen) """ by_name = {} for path in icon_paths: by_name.setdefault(os.path.basename(path), []).append(path) chosen = {} collisions = {} for name in sorted(by_name): # Feste Reihenfolge statt Zufall: Pfade unter /aion2/maps/... (dort liegen fast alle # Icons) zuerst. Die uebrigen biegt der Viewer ueber CONFIG.ICON_ALIASES (js/config.js) um. paths = sorted(by_name[name], key=lambda p: (not p.startswith("/aion2/"), p)) chosen[name] = paths[0] if len(paths) > 1: collisions[name] = paths return chosen, collisions def download_icon(icon_path, out_dir, retries=3): """Download a single icon. Returns (status, filename).""" # Extract filename from path filename = os.path.basename(icon_path) if not filename: return "error:no-filename", icon_path dest = os.path.join(out_dir, filename) if os.path.exists(dest) and os.path.getsize(dest) > 0: return "exists", filename url = BASE_URL + icon_path tmp = dest + ".part" status = "error:unknown" # Bis zu 3 Versuche wie fetch_tile in download_all_maps.py; 404 gibt es an der Quelle nicht. 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: data = resp.read() if data: with open(tmp, "wb") as fh: fh.write(data) os.replace(tmp, dest) return "ok", filename status = "empty" except urllib.error.HTTPError as e: if e.code == 404: return "missing", filename status = f"error:HTTP {e.code}" except Exception as e: status = f"error:{e!r}" if attempt < retries: time.sleep(0.5 * attempt) # Halbe Datei eines abgebrochenen Versuchs nicht liegen lassen try: os.unlink(tmp) except OSError: pass return status, filename def main(): parser = argparse.ArgumentParser(description="Download all unique marker icon graphics") parser.add_argument("-m", "--markers-dir", default="../data/markers", help="Directory containing marker JSON files") parser.add_argument("-o", "--out-dir", default="../data/icons", help="Output directory for icons") parser.add_argument("-w", "--workers", type=int, default=16, help="Number of concurrent downloads") args = parser.parse_args() # Resolve directories relative to script location script_dir = os.path.dirname(os.path.abspath(__file__)) markers_dir = os.path.join(script_dir, args.markers_dir) if not os.path.isabs(args.markers_dir) else args.markers_dir out_dir = os.path.join(script_dir, args.out_dir) if not os.path.isabs(args.out_dir) else args.out_dir # Collect unique icons from all marker files icon_paths = collect_unique_icons(markers_dir) if not icon_paths: print("No icons found. Run extract_all_markers.py first.") sys.exit(1) # Pro Dateiname nur ein Download (siehe pick_one_path_per_filename) chosen, collisions = pick_one_path_per_filename(icon_paths) if collisions: print(f"\nWARNING: {len(collisions)} file name(s) are used by different source paths.") print(" Only one path per name is downloaded (an existing file is kept as it is).") print(" The viewer maps the other paths via CONFIG.ICON_ALIASES in js/config.js - check it:") for name, paths in collisions.items(): print(f" {name}") print(f" saved as {name}: {paths[0]}") for other in paths[1:]: print(f" not downloaded: {other}") # Create output directory os.makedirs(out_dir, exist_ok=True) # Download all icons total = len(chosen) print(f"\nDownloading {total} icons to: {out_dir}") counts = {"ok": 0, "exists": 0, "missing": 0, "empty": 0, "error": 0} problems = [] # (Dateiname, Status, Quellpfad) - am Ende mit Namen ausgeben done = 0 t0 = time.time() with ThreadPoolExecutor(max_workers=args.workers) as pool: futures = {} for icon_path in chosen.values(): futures[pool.submit(download_icon, icon_path, out_dir)] = icon_path for fut in as_completed(futures): icon_path = futures[fut] status, filename = fut.result() kind = status.split(":", 1)[0] counts[kind] = counts.get(kind, 0) + 1 if kind not in ("ok", "exists"): problems.append((filename, status, icon_path)) done += 1 if done % max(1, total // 10) == 0 or done == total: rate = done / max(time.time() - t0, 1e-6) print(f" {done}/{total} ({rate:.1f}/s) " f"ok={counts['ok']} cached={counts['exists']} missing={counts['missing']} " f"empty={counts['empty']} err={counts['error']}", flush=True) elapsed = time.time() - t0 print(f"\nDone in {elapsed:.0f}s: downloaded={counts['ok']} cached={counts['exists']} " f"missing={counts['missing']} empty={counts['empty']} failed={counts['error']}") print(f"Icons saved to: {out_dir}") if problems: print(f"\n{len(problems)} icon(s) could not be downloaded:") for filename, status, icon_path in sorted(problems): print(f" {filename} [{status}] {BASE_URL}{icon_path}") if collisions: print(f"\nNote: {len(collisions)} file name collision(s), see the warning above.") if __name__ == "__main__": main()