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:
70
.gitignore
vendored
Normal file
70
.gitignore
vendored
Normal 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__/
|
||||
208
dashboard.html
208
dashboard.html
@ -118,6 +118,21 @@
|
||||
.full-width {
|
||||
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>
|
||||
</head>
|
||||
<body>
|
||||
@ -145,15 +160,13 @@
|
||||
|
||||
<button class="refresh-btn" onclick="refreshAll()">Aktualisieren</button>
|
||||
|
||||
<div class="status-bar" id="status"></div>
|
||||
|
||||
<script>
|
||||
// ABS Configuration
|
||||
const ABS_BASE_URL = 'https://abs.sphinx-morray.ts.net/audiobookshelf';
|
||||
const ABS_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXlJZCI6IjFiZTdiZmIzLTE1NGYtNGE3Yy1hMTFjLTZkNDg3YWNhMWZiYyIsIm5hbWUiOiJEYXNoYm9hcmQiLCJ0eXBlIjoiYXBpIiwiaWF0IjoxNzkzNjU0NjA3LCJleHAiOjE3OTM2ODYxNDJ9.h3284mhyio4GIIfAFoa6D6KXiUNWzGy622SiARqTplE';
|
||||
// API endpoint (change this if your server runs on a different port)
|
||||
const API_URL = '/api/dashboard';
|
||||
|
||||
// Wetter Configuration (Aachen: 50.7769, 6.0834)
|
||||
const WEATHER_URL = 'https://api.open-meteo.com/v1/forecast?latitude=50.7769&longitude=6.0834¤t_weather=true&timezone=Europe/Berlin';
|
||||
|
||||
// Wettercode zu Text Mapping (WMO Codes)
|
||||
// Wettercode zu Text Mapping (WMO codes)
|
||||
const weatherCodes = {
|
||||
0: { icon: '☀️', text: 'Klarer Himmel' },
|
||||
1: { icon: '⛅', text: 'Überwiegend klar' },
|
||||
@ -196,113 +209,97 @@
|
||||
document.getElementById('date').textContent = now.toLocaleDateString('de-DE', dateOptions);
|
||||
}
|
||||
|
||||
// Wetterdaten holen
|
||||
async function fetchWeather() {
|
||||
try {
|
||||
const response = await fetch(WEATHER_URL);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.current_weather) {
|
||||
const weather = data.current_weather;
|
||||
const code = weather.weathercode;
|
||||
const weatherInfo = weatherCodes[code] || { icon: '🌐', 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' });
|
||||
|
||||
document.getElementById('weather').innerHTML = `
|
||||
<div class="weather-container">
|
||||
<div class="weather-icon">${weatherInfo.icon}</div>
|
||||
<div class="weather-details">
|
||||
<div class="card-value">${temp}°C</div>
|
||||
<div class="card-subvalue">${weatherInfo.text}</div>
|
||||
<div class="card-subvalue">Wind: ${wind} km/h</div>
|
||||
<div class="card-subvalue">Aktualisiert: ${time}</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
} catch (error) {
|
||||
// Wetterdaten anzeigen
|
||||
function displayWeather(weather) {
|
||||
if (!weather) {
|
||||
document.getElementById('weather').innerHTML = '<span class="error">Wetterdaten nicht verfügbar</span>';
|
||||
console.error('Wetter-API Fehler:', error);
|
||||
return;
|
||||
}
|
||||
|
||||
const temp = weather.temperature;
|
||||
const wind = weather.windspeed;
|
||||
const icon = weather.icon || '🌐';
|
||||
const text = weather.text || 'Unbekannt';
|
||||
const time = new Date(weather.time).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
|
||||
|
||||
document.getElementById('weather').innerHTML = `
|
||||
<div class="weather-container">
|
||||
<div class="weather-icon">${icon}</div>
|
||||
<div class="weather-details">
|
||||
<div class="card-value">${temp}°C</div>
|
||||
<div class="card-subvalue">${text}</div>
|
||||
<div class="card-subvalue">Wind: ${wind} km/h</div>
|
||||
<div class="card-subvalue">Aktualisiert: ${time}</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// ABS Daten holen
|
||||
async function fetchAudiobook() {
|
||||
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();
|
||||
|
||||
if (userData.mediaProgress && userData.mediaProgress.length > 0) {
|
||||
// Nach dem zuletzt aktualisierten Element sortieren
|
||||
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 = `
|
||||
<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">Fortschritt: ${progressPercent}% (${currentTime}/${duration})</div>
|
||||
`;
|
||||
} else {
|
||||
document.getElementById('audiobook').innerHTML = '<span class="card-subvalue">Kein aktuell gehörtes Hörbuch</span>';
|
||||
}
|
||||
} catch (error) {
|
||||
// ABS-Daten anzeigen
|
||||
function displayAudiobook(absData) {
|
||||
if (!absData) {
|
||||
document.getElementById('audiobook').innerHTML = '<span class="error">ABS-Daten nicht verfügbar</span>';
|
||||
console.error('ABS-API Fehler:', error);
|
||||
return;
|
||||
}
|
||||
|
||||
let displayText = absData.title;
|
||||
if (absData.author) displayText = `${absData.title} – ${absData.author}`;
|
||||
|
||||
const mediaType = absData.mediaType === 'podcast' ? '🎙️ Podcast' : (absData.mediaType === 'book' ? '📖 Hörbuch' : '📚 Medium');
|
||||
const progressPercent = absData.progress;
|
||||
const currentTime = absData.currentTime;
|
||||
const duration = absData.duration;
|
||||
|
||||
document.getElementById('audiobook').innerHTML = `
|
||||
<div class="card-value" style="font-size: 1.25rem;">${displayText}</div>
|
||||
<div class="card-subvalue">${mediaType}</div>
|
||||
<div class="card-subvalue">Fortschritt: ${progressPercent}% (${currentTime}/${duration})</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 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) {
|
||||
console.error('API-Fehler:', error);
|
||||
updateStatus(`Fehler: ${error.message}`, 'error');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Dauer formatieren (Sekunden zu HH:MM:SS)
|
||||
function formatDuration(seconds) {
|
||||
if (!seconds) return '0:00';
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
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')}`;
|
||||
// Status anzeigen
|
||||
function updateStatus(message, type = '') {
|
||||
const statusEl = document.getElementById('status');
|
||||
statusEl.textContent = message;
|
||||
statusEl.className = type;
|
||||
}
|
||||
|
||||
// Alle Daten aktualisieren
|
||||
async function refreshAll() {
|
||||
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
|
||||
@ -317,6 +314,15 @@
|
||||
|
||||
// Bei Fokus zurückkehren auch aktualisieren
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
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)
|
||||
2
requirements.txt
Normal file
2
requirements.txt
Normal file
@ -0,0 +1,2 @@
|
||||
Flask>=2.0.0
|
||||
requests>=2.25.0
|
||||
Reference in New Issue
Block a user