LuminaWebsite/assets/map/scripts/download_marker_icons.py
Maaxxs c4f94bf84a Member feedback: raid input checks and fixed raid points, premades in the raid form, live raid page, Lumina-style dialogs, leadership calendar entries, class-based weapon picker, map and tactics fixes
- Raids: "Max. Spieler" only whole numbers up to groups x 5 (max. 10 groups / 50), gearscore only a number; fixed +1 Lumipunkt per participation, other values only with the new raids.points permission; pick an existing premade per group when creating a raid; unchanged legacy values no longer block editing
- Raid page updates itself every 15 s while visible (raids_live.php, cards rendered by includes/raid_card.php), open editors and confirm dialogs are kept
- Restore takes the new raid_id from the bot (archived messages are now deleted in Discord) and moves settings, attendance and awards; website signups send the server display name
- Premades: dissolve by leadership needs a reason, lead gets DMs on join/assign/decline/remove (source/actor_id sent to the bot), transfer picker skips players who already lead a group, website accept keeps the one-group rule, no commas in names
- Site-wide Lumina dialog (assets/js/confirm-dialog.js) replaces confirm/prompt/alert via data-confirm; error flashes are a dialog you confirm with OK
- Calendar: audience per entry (all / leadership takes part / internal) with the new calendar.leadership permission; day cells list all entries and scroll
- Gear planner: main-hand picker filtered by the set's class, mismatches marked, "keine Klasse" option, link to an external skill/Daevanion plan per set
- Map: correct kisk icons (Elyos on Verteron/Abyss, Altgard fixed), per-map max zoom and bounded panning, German texts, data source note
- Tactics: toolbar as a uniform grid, whole-tactic copy, automatic versions with restore and a 90-day trash, official tactics protected
- Global thin gold scrollbars, readable hover colours, "Sedes Luminis" spelling, patch notes and README, schema version 34

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 16:12:18 +02:00

212 lines
No EOL
8.2 KiB
Python

#!/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()