Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 116 additions & 28 deletions api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,40 @@ async def callback_message_received(msg):


# init messaging
message_api_request = Message("127.0.0.1", 6969)
event_host = os.environ.get("EVENT_HOST", "127.0.0.1")
message_api_request = Message(event_host, 6969)


@app.route("/")
def index():
# Configure tile servers with proper HTTPS
tile_servers = {
"esri": os.getenv(
"TILE_SERVER_ESRI",
"tile.openstreetmap.org/{z}/{x}/{y}.png",
),
"mapbox_streets": os.getenv(
"TILE_SERVER_MAPBOX_STREETS",
"tile.openstreetmap.org/{z}/{x}/{y}.png",
),
"mapbox_dark": os.getenv(
"TILE_SERVER_MAPBOX_DARK",
"tile.openstreetmap.org/{z}/{x}/{y}.png",
),
"opentopomap": os.getenv(
"TILE_SERVER_OPENTOPOMAP",
"tile.openstreetmap.org/{z}/{x}/{y}.png",
),
"esri_satellite": os.getenv(
"TILE_SERVER_ESRI_SATELLITE",
"server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
),
"google_satellite": os.getenv(
"TILE_SERVER_GOOGLE_SATELLITE",
"mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}",
),
}

app_config = {
"map": {
"location": {
Expand All @@ -105,33 +134,25 @@ def index():
},
"center_width": int(os.getenv("MAP_CENTER_WIDTH", 50000)),
"center_height": int(os.getenv("MAP_CENTER_HEIGHT", 40000)),
"tile_server": {
"esri": os.getenv(
"TILE_SERVER_ESRI",
"tile.datr.dev/data/esri-adelaide/",
),
"mapbox_streets": os.getenv(
"TILE_SERVER_MAPBOX_STREETS",
"tile.datr.dev/data/mapbox-streets-v11/",
),
"mapbox_dark": os.getenv(
"TILE_SERVER_MAPBOX_DARK",
"tile.datr.dev/data/mapbox-dark-v10/",
),
"opentopomap": os.getenv(
"TILE_SERVER_OPENTOPOMAP",
"tile.datr.dev/data/opentopomap/",
),
},
"tile_server": ensure_tile_server_https(tile_servers),
"tar1090": os.getenv("TAR1090_URL", "localhost:5001"),
},
}

# Translate container URLs to localhost URLs for browser
browser_servers = translate_container_to_browser_urls(servers)
browser_adsbs = []
for adsb in adsbs:
browser_adsb = adsb.copy()
browser_adsb["url"] = browser_adsb["url"].replace("synthetic-adsb:", "localhost:")
browser_adsbs.append(browser_adsb)

return render_template(
"index.html",
servers=servers,
servers=browser_servers,
associators=associators,
localisations=localisations,
adsbs=adsbs,
adsbs=browser_adsbs,
app_config=app_config,
config_json=json.dumps(app_config),
)
Expand All @@ -145,6 +166,32 @@ def serve_static(file):
return send_from_directory(public_folder, file)


def translate_browser_to_container_urls(url_list, url_type="server"):
"""Translate localhost URLs from browser to container URLs for internal processing"""
translated = []
for url in url_list:
# Translate localhost URLs to container URLs
container_url = url.replace("localhost:", "synthetic-adsb:")
translated.append(container_url)
return translated

def translate_container_to_browser_urls(server_list):
"""Translate container URLs to localhost URLs for browser consumption"""
browser_servers = []
for server in server_list:
browser_server = server.copy()
# Translate synthetic-adsb container URLs to localhost URLs
browser_server["url"] = browser_server["url"].replace("synthetic-adsb:", "localhost:")
browser_servers.append(browser_server)
return browser_servers

def ensure_tile_server_https(tile_config):
"""Ensure tile server URLs have https:// prefix"""
for key, url in tile_config.items():
if url and not url.startswith(('http://', 'https://')):
tile_config[key] = f"https://{url}"
return tile_config

@app.route("/api")
def api():
api = request.query_string.decode("utf-8")
Expand All @@ -153,22 +200,54 @@ def api():
associators_api = request.args.getlist("associator")
localisations_api = request.args.getlist("localisation")
adsbs_api = request.args.getlist("adsb")
if not all(item in valid["servers"] for item in servers_api):

# Translate localhost URLs to container URLs for internal validation and processing
servers_translated = translate_browser_to_container_urls(servers_api, "server")
adsbs_translated = translate_browser_to_container_urls(adsbs_api, "adsb")

print(f"[DEBUG] Original servers: {servers_api}", flush=True)
print(f"[DEBUG] Translated servers: {servers_translated}", flush=True)
print(f"[DEBUG] Valid servers list: {valid['servers']}", flush=True)

if not all(item in valid["servers"] for item in servers_translated):
print(f"[DEBUG] Server validation failed for translated: {servers_translated}", flush=True)
return "Invalid server"
if not all(item in valid["associators"] for item in associators_api):
return "Invalid associator"
if not all(item in valid["localisations"] for item in localisations_api):
return "Invalid localisation"
if not all(item in valid["adsbs"] for item in adsbs_api):
if not all(item in valid["adsbs"] for item in adsbs_translated):
return "Invalid ADSB"

# Reconstruct API query string with translated container URLs for event processing
api_parts = []
for server in servers_translated:
api_parts.append(f"server={server}")
for adsb in adsbs_translated:
api_parts.append(f"adsb={adsb}")
for assoc in associators_api:
api_parts.append(f"associator={assoc}")
for loc in localisations_api:
api_parts.append(f"localisation={loc}")

translated_api = "&".join(api_parts)

# send to event handler
try:
print(f"Sending API request: {api}", flush=True)
reply_chunks = message_api_request.send_message(api)
print(f"Sending original API request: {api}", flush=True)
print(f"Sending translated API request: {translated_api}", flush=True)
reply_chunks = message_api_request.send_message(translated_api)
print("Got reply_chunks generator", flush=True)
reply = "".join(reply_chunks)
print(f"Final reply: {reply}", flush=True)
return reply
# Parse the JSON string and return it as proper JSON response
import json
try:
reply_data = json.loads(reply)
return jsonify(reply_data)
except json.JSONDecodeError:
# If it's not valid JSON, return as-is with JSON error wrapper
return jsonify({"error": "Invalid JSON response", "raw": reply})
except Exception as e:
import traceback
error_trace = traceback.format_exc()
Expand All @@ -182,7 +261,15 @@ def api():
def serve_map(file):
base_dir = os.path.abspath(os.path.dirname(__file__))
public_folder = os.path.join(base_dir, "map")
return send_from_directory(public_folder, file)
response = send_from_directory(public_folder, file)

# Add no-cache headers for JavaScript files to prevent browser caching during development
if file.endswith('.js'):
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'

return response


# handle /cesium/ specifically
Expand All @@ -193,7 +280,8 @@ def serve_cesium_index():

@app.route("/cesium/<path:file>")
def serve_cesium_content(file):
apache_url = "http://127.0.0.1:8080/" + file
cesium_host = os.environ.get("CESIUM_HOST", "127.0.0.1")
apache_url = f"http://{cesium_host}:8080/" + file
try:
response = requests.get(apache_url, timeout=10)
if response.status_code == 200:
Expand Down
29 changes: 27 additions & 2 deletions api/map/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<title>3lips Map</title>
<script src="/cesium/Build/Cesium/Cesium.js"></script>
<script src="https://cesium.com/downloads/cesiumjs/releases/1.114/Build/Cesium/Cesium.js"></script>
<style>
@import url(/cesium/Build/Cesium/Widgets/widgets.css);
@import url(https://cesium.com/downloads/cesiumjs/releases/1.114/Build/Cesium/Widgets/widgets.css);

html,
body,
Expand Down Expand Up @@ -132,12 +132,37 @@ <h4>🎯 Track Legend</h4>
if (configParam) {
try {
window.APP_CONFIG = JSON.parse(decodeURIComponent(configParam));
console.log('Config loaded from URL:', window.APP_CONFIG);
} catch (e) {
console.error('Map page - Error parsing config:', e);
}
} else {
console.error('No config found in URL parameters');
}

// Fallback config if APP_CONFIG is not loaded
if (!window.APP_CONFIG) {
console.log('Using fallback config with updated tile servers');
window.APP_CONFIG = {
"map": {
"location": {
"latitude": -34.9286,
"longitude": 138.5999
},
"center_width": 50000,
"center_height": 40000,
"tile_server": {
"esri": "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
"mapbox_streets": "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png",
"mapbox_dark": "https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png",
"opentopomap": "https://tile.opentopomap.org/{z}/{x}/{y}.png",
"esri_satellite": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
"google_satellite": "https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}"
},
"tar1090": "http://synthetic-adsb:5001"
}
};
}
</script>
<script src="lib/jquery-3.6.0.min.js"></script>
<script src="event/adsb.js"></script>
Expand Down
Loading
Loading