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:
wralto-user-1
2026-11-02 22:33:38 +01:00
parent 2567d807e2
commit a61fc8d7d1
4 changed files with 351 additions and 105 deletions

70
.gitignore vendored Normal file
View File

@ -0,0 +1,70 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# IDE
.idea/
.vscode/
*.swp
*.swo
# pytest
.pytest_cache/
__pycache__/

View File

@ -118,6 +118,21 @@
.full-width { .full-width {
grid-column: 1 / -1; grid-column: 1 / -1;
} }
.status-bar {
margin-top: 2rem;
font-size: 0.75rem;
color: #666;
text-align: center;
}
.status-bar .error {
color: #ff4444;
}
.status-bar .success {
color: #44ff44;
}
</style> </style>
</head> </head>
<body> <body>
@ -145,15 +160,13 @@
<button class="refresh-btn" onclick="refreshAll()">Aktualisieren</button> <button class="refresh-btn" onclick="refreshAll()">Aktualisieren</button>
<div class="status-bar" id="status"></div>
<script> <script>
// ABS Configuration // API endpoint (change this if your server runs on a different port)
const ABS_BASE_URL = 'https://abs.sphinx-morray.ts.net/audiobookshelf'; const API_URL = '/api/dashboard';
const ABS_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXlJZCI6IjFiZTdiZmIzLTE1NGYtNGE3Yy1hMTFjLTZkNDg3YWNhMWZiYyIsIm5hbWUiOiJEYXNoYm9hcmQiLCJ0eXBlIjoiYXBpIiwiaWF0IjoxNzkzNjU0NjA3LCJleHAiOjE3OTM2ODYxNDJ9.h3284mhyio4GIIfAFoa6D6KXiUNWzGy622SiARqTplE';
// Wetter Configuration (Aachen: 50.7769, 6.0834) // Wettercode zu Text Mapping (WMO codes)
const WEATHER_URL = 'https://api.open-meteo.com/v1/forecast?latitude=50.7769&longitude=6.0834&current_weather=true&timezone=Europe/Berlin';
// Wettercode zu Text Mapping (WMO Codes)
const weatherCodes = { const weatherCodes = {
0: { icon: '☀️', text: 'Klarer Himmel' }, 0: { icon: '☀️', text: 'Klarer Himmel' },
1: { icon: '⛅', text: 'Überwiegend klar' }, 1: { icon: '⛅', text: 'Überwiegend klar' },
@ -196,113 +209,97 @@
document.getElementById('date').textContent = now.toLocaleDateString('de-DE', dateOptions); document.getElementById('date').textContent = now.toLocaleDateString('de-DE', dateOptions);
} }
// Wetterdaten holen // Wetterdaten anzeigen
async function fetchWeather() { function displayWeather(weather) {
try { if (!weather) {
const response = await fetch(WEATHER_URL); document.getElementById('weather').innerHTML = '<span class="error">Wetterdaten nicht verfügbar</span>';
const data = await response.json(); return;
}
if (data.current_weather) { const temp = weather.temperature;
const weather = data.current_weather; const wind = weather.windspeed;
const code = weather.weathercode; const icon = weather.icon || '🌐';
const weatherInfo = weatherCodes[code] || { icon: '🌐', text: 'Unbekannt' }; const text = weather.text || 'Unbekannt';
const temp = Math.round(weather.temperature * 10) / 10;
const wind = Math.round(weather.windspeed * 10) / 10;
const time = new Date(weather.time).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }); const time = new Date(weather.time).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
document.getElementById('weather').innerHTML = ` document.getElementById('weather').innerHTML = `
<div class="weather-container"> <div class="weather-container">
<div class="weather-icon">${weatherInfo.icon}</div> <div class="weather-icon">${icon}</div>
<div class="weather-details"> <div class="weather-details">
<div class="card-value">${temp}°C</div> <div class="card-value">${temp}°C</div>
<div class="card-subvalue">${weatherInfo.text}</div> <div class="card-subvalue">${text}</div>
<div class="card-subvalue">Wind: ${wind} km/h</div> <div class="card-subvalue">Wind: ${wind} km/h</div>
<div class="card-subvalue">Aktualisiert: ${time}</div> <div class="card-subvalue">Aktualisiert: ${time}</div>
</div> </div>
</div> </div>
`; `;
} }
} catch (error) {
document.getElementById('weather').innerHTML = '<span class="error">Wetterdaten nicht verfügbar</span>'; // ABS-Daten anzeigen
console.error('Wetter-API Fehler:', error); function displayAudiobook(absData) {
} if (!absData) {
document.getElementById('audiobook').innerHTML = '<span class="error">ABS-Daten nicht verfügbar</span>';
return;
} }
// ABS Daten holen let displayText = absData.title;
async function fetchAudiobook() { if (absData.author) displayText = `${absData.title} – ${absData.author}`;
try {
// Benutzerdaten mit Fortschritt holen
const response = await fetch(`${ABS_BASE_URL}/api/me`, {
headers: {
'Authorization': `Bearer ${ABS_TOKEN}`,
'Content-Type': 'application/json'
}
});
const userData = await response.json(); const mediaType = absData.mediaType === 'podcast' ? '🎙️ Podcast' : (absData.mediaType === 'book' ? '📖 Hörbuch' : '📚 Medium');
const progressPercent = absData.progress;
if (userData.mediaProgress && userData.mediaProgress.length > 0) { const currentTime = absData.currentTime;
// Nach dem zuletzt aktualisierten Element sortieren const duration = absData.duration;
const sortedProgress = [...userData.mediaProgress].sort((a, b) =>
new Date(b.lastUpdate) - new Date(a.lastUpdate)
);
const latest = sortedProgress[0];
const libraryItemId = latest.libraryItemId;
// Details des Hörbuchs/Podcasts holen
const itemResponse = await fetch(`${ABS_BASE_URL}/api/items/${libraryItemId}`, {
headers: {
'Authorization': `Bearer ${ABS_TOKEN}`,
'Content-Type': 'application/json'
}
});
const itemData = await itemResponse.json();
const title = itemData.media?.metadata?.title || 'Unbekannt';
const author = itemData.media?.metadata?.author || '';
const mediaType = itemData.mediaType || 'item';
let displayText = title;
if (author) displayText = `${title} – ${author}`;
// Fortschritt anzeigen
const progressPercent = Math.round(latest.progress * 100);
const currentTime = formatDuration(latest.currentTime);
const duration = formatDuration(latest.duration);
document.getElementById('audiobook').innerHTML = ` document.getElementById('audiobook').innerHTML = `
<div class="card-value" style="font-size: 1.25rem;">${displayText}</div> <div class="card-value" style="font-size: 1.25rem;">${displayText}</div>
<div class="card-subvalue">${mediaType === 'podcast' ? '🎙️ Podcast' : '📖 Hörbuch'}</div> <div class="card-subvalue">${mediaType}</div>
<div class="card-subvalue">Fortschritt: ${progressPercent}% (${currentTime}/${duration})</div> <div class="card-subvalue">Fortschritt: ${progressPercent}% (${currentTime}/${duration})</div>
`; `;
} else {
document.getElementById('audiobook').innerHTML = '<span class="card-subvalue">Kein aktuell gehörtes Hörbuch</span>';
} }
// Alle Daten von der API holen
async function fetchDashboardData() {
try {
const response = await fetch(API_URL);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) { } catch (error) {
document.getElementById('audiobook').innerHTML = '<span class="error">ABS-Daten nicht verfügbar</span>'; console.error('API-Fehler:', error);
console.error('ABS-API Fehler:', error); updateStatus(`Fehler: ${error.message}`, 'error');
return null;
} }
} }
// Dauer formatieren (Sekunden zu HH:MM:SS) // Status anzeigen
function formatDuration(seconds) { function updateStatus(message, type = '') {
if (!seconds) return '0:00'; const statusEl = document.getElementById('status');
const hours = Math.floor(seconds / 3600); statusEl.textContent = message;
const minutes = Math.floor((seconds % 3600) / 60); statusEl.className = type;
const secs = Math.floor(seconds % 60);
if (hours > 0) {
return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
return `${minutes}:${secs.toString().padStart(2, '0')}`;
} }
// Alle Daten aktualisieren // Alle Daten aktualisieren
async function refreshAll() { async function refreshAll() {
updateClock(); updateClock();
await Promise.all([fetchWeather(), fetchAudiobook()]); updateStatus('Lade Daten...', 'loading');
try {
const data = await fetchDashboardData();
if (data) {
displayWeather(data.weather);
displayAudiobook(data.audiobook);
updateStatus('Daten erfolgreich geladen', 'success');
} else {
updateStatus('Keine Daten erhalten', 'error');
}
} catch (error) {
updateStatus(`Fehler: ${error.message}`, 'error');
}
} }
// Initial laden // Initial laden
@ -317,6 +314,15 @@
// Bei Fokus zurückkehren auch aktualisieren // Bei Fokus zurückkehren auch aktualisieren
window.addEventListener('focus', refreshAll); window.addEventListener('focus', refreshAll);
// Status nach 5 Sekunden zurücksetzen
setTimeout(() => {
const statusEl = document.getElementById('status');
if (statusEl.className === 'success') {
statusEl.textContent = '';
statusEl.className = '';
}
}, 5000);
</script> </script>
</body> </body>
</html> </html>

168
dashboard_api.py Normal file
View 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&current_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)

2
requirements.txt Normal file
View File

@ -0,0 +1,2 @@
Flask>=2.0.0
requests>=2.25.0