feat: add Flask API server for dashboard to avoid CORS issues with ABS
- Add dashboard_api.py as backend proxy for ABS and weather data - Update dashboard.html to fetch data from local API instead of directly - Add requirements.txt for Flask dependencies - Add .gitignore for Python and pytest files Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
168
dashboard_api.py
Normal file
168
dashboard_api.py
Normal file
@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Dashboard API Server
|
||||
Provides a simple API endpoint that aggregates weather and ABS data for the dashboard.
|
||||
This avoids CORS issues with the ABS API.
|
||||
|
||||
Run with: python3 dashboard_api.py
|
||||
Access: http://localhost:5000/api/dashboard
|
||||
"""
|
||||
|
||||
import requests
|
||||
from flask import Flask, jsonify
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Configuration
|
||||
ABS_BASE_URL = "https://abs.sphinx-morray.ts.net/audiobookshelf"
|
||||
ABS_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXlJZCI6IjFiZTdiZmIzLTE1NGYtNGE3Yy1hMTFjLTZkNDg3YWNhMWZiYyIsIm5hbWUiOiJEYXNoYm9hcmQiLCJ0eXBlIjoiYXBpIiwiaWF0IjoxNzkzNjU0NjA3LCJleHAiOjE3OTM2ODYxNDJ9.h3284mhyio4GIIfAFoa6D6KXiUNWzGy622SiARqTplE"
|
||||
WEATHER_URL = "https://api.open-meteo.com/v1/forecast?latitude=50.7769&longitude=6.0834¤t_weather=true&timezone=Europe/Berlin"
|
||||
|
||||
# Weather code mapping (WMO codes)
|
||||
WEATHER_CODES = {
|
||||
0: {"icon": "☀️", "text": "Klarer Himmel"},
|
||||
1: {"icon": "⛅", "text": "Überwiegend klar"},
|
||||
2: {"icon": "⛅", "text": "Teilweise bewölkt"},
|
||||
3: {"icon": "☁️", "text": "Bedeckt"},
|
||||
45: {"icon": "🌫️", "text": "Nebel"},
|
||||
48: {"icon": "🌫️", "text": "Gefrierender Nebel"},
|
||||
51: {"icon": "🌦️", "text": "Leichter Nieselregen"},
|
||||
53: {"icon": "🌧️", "text": "Mäßiger Nieselregen"},
|
||||
55: {"icon": "🌧️", "text": "Starker Nieselregen"},
|
||||
56: {"icon": "🌦️", "text": "Leichter gefrierender Nieselregen"},
|
||||
57: {"icon": "🌧️", "text": "Starker gefrierender Nieselregen"},
|
||||
61: {"icon": "🌦️", "text": "Leichter Regen"},
|
||||
63: {"icon": "🌧️", "text": "Mäßiger Regen"},
|
||||
65: {"icon": "🌧️", "text": "Starker Regen"},
|
||||
66: {"icon": "🌦️", "text": "Leichter gefrierender Regen"},
|
||||
67: {"icon": "🌧️", "text": "Starker gefrierender Regen"},
|
||||
71: {"icon": "❄️", "text": "Leichter Schneefall"},
|
||||
73: {"icon": "❄️", "text": "Mäßiger Schneefall"},
|
||||
75: {"icon": "❄️", "text": "Starker Schneefall"},
|
||||
77: {"icon": "❄️", "text": "Schneegriesel"},
|
||||
80: {"icon": "🌦️", "text": "Leichte Regenschauer"},
|
||||
81: {"icon": "🌧️", "text": "Mäßige Regenschauer"},
|
||||
82: {"icon": "🌧️", "text": "Heftige Regenschauer"},
|
||||
85: {"icon": "❄️", "text": "Leichte Schneeschauer"},
|
||||
86: {"icon": "❄️", "text": "Heftige Schneeschauer"},
|
||||
95: {"icon": "⛈️", "text": "Gewitter"},
|
||||
96: {"icon": "⛈️", "text": "Gewitter mit leichtem Hagel"},
|
||||
99: {"icon": "⛈️", "text": "Gewitter mit starkem Hagel"},
|
||||
}
|
||||
|
||||
|
||||
def format_duration(seconds):
|
||||
"""Format seconds to HH:MM:SS or MM:SS"""
|
||||
if not seconds:
|
||||
return "0:00"
|
||||
hours = int(seconds // 3600)
|
||||
minutes = int((seconds % 3600) // 60)
|
||||
secs = int(seconds % 60)
|
||||
if hours > 0:
|
||||
return f"{hours}:{minutes:02d}:{secs:02d}"
|
||||
return f"{minutes}:{secs:02d}"
|
||||
|
||||
|
||||
def fetch_weather():
|
||||
"""Fetch weather data from Open-Meteo"""
|
||||
try:
|
||||
response = requests.get(WEATHER_URL, timeout=10)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
if "current_weather" in data:
|
||||
weather = data["current_weather"]
|
||||
code = weather["weathercode"]
|
||||
weather_info = WEATHER_CODES.get(code, {"icon": "🌐", "text": "Unbekannt"})
|
||||
|
||||
return {
|
||||
"temperature": round(weather["temperature"], 1),
|
||||
"windspeed": round(weather["windspeed"], 1),
|
||||
"icon": weather_info["icon"],
|
||||
"text": weather_info["text"],
|
||||
"time": weather["time"],
|
||||
}
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"Weather API error: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def fetch_abs_data():
|
||||
"""Fetch ABS user data and latest audiobook"""
|
||||
try:
|
||||
headers = {
|
||||
"Authorization": f"Bearer {ABS_TOKEN}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
# Get user data with progress
|
||||
response = requests.get(f"{ABS_BASE_URL}/api/me", headers=headers, timeout=10)
|
||||
response.raise_for_status()
|
||||
user_data = response.json()
|
||||
|
||||
if "mediaProgress" in user_data and user_data["mediaProgress"]:
|
||||
# Sort by lastUpdate, get latest
|
||||
sorted_progress = sorted(
|
||||
user_data["mediaProgress"],
|
||||
key=lambda x: x.get("lastUpdate", 0),
|
||||
reverse=True,
|
||||
)
|
||||
latest = sorted_progress[0]
|
||||
library_item_id = latest.get("libraryItemId")
|
||||
|
||||
# Get item details
|
||||
item_response = requests.get(
|
||||
f"{ABS_BASE_URL}/api/items/{library_item_id}",
|
||||
headers=headers,
|
||||
timeout=10,
|
||||
)
|
||||
item_response.raise_for_status()
|
||||
item_data = item_response.json()
|
||||
|
||||
metadata = item_data.get("media", {}).get("metadata", {})
|
||||
title = metadata.get("title", "Unbekannt")
|
||||
author = metadata.get("author", "")
|
||||
media_type = item_data.get("mediaType", "item")
|
||||
|
||||
return {
|
||||
"title": title,
|
||||
"author": author,
|
||||
"mediaType": media_type,
|
||||
"progress": round(latest.get("progress", 0) * 100),
|
||||
"currentTime": format_duration(latest.get("currentTime", 0)),
|
||||
"duration": format_duration(latest.get("duration", 0)),
|
||||
}
|
||||
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"ABS API error: {e}")
|
||||
return None
|
||||
|
||||
|
||||
@app.route("/api/dashboard")
|
||||
def get_dashboard_data():
|
||||
"""Return combined dashboard data"""
|
||||
weather = fetch_weather()
|
||||
abs_data = fetch_abs_data()
|
||||
|
||||
return jsonify({
|
||||
"weather": weather,
|
||||
"audiobook": abs_data,
|
||||
})
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def serve_dashboard():
|
||||
"""Serve the dashboard HTML"""
|
||||
return app.send_static_file("dashboard.html")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Check if we're in the right directory
|
||||
if not os.path.exists("dashboard.html"):
|
||||
print("Error: dashboard.html not found. Please run from the project directory.")
|
||||
exit(1)
|
||||
|
||||
app.run(host="0.0.0.0", port=5000, debug=False)
|
||||
Reference in New Issue
Block a user