675 lines
31 KiB
Python
675 lines
31 KiB
Python
import os
|
|
import json
|
|
import io
|
|
import zipfile
|
|
import asyncio
|
|
from pathlib import Path
|
|
from flask import Flask, render_template_string, request, session, redirect, url_for, send_from_directory, send_file, jsonify
|
|
from flask_cors import CORS
|
|
from playwright.async_api import async_playwright
|
|
import requests
|
|
|
|
# Konfiguration
|
|
PASSWORD = 'toniessindteuer'
|
|
BASE_DIR = '/mnt/NAS/Toniebox/'
|
|
|
|
app = Flask(__name__)
|
|
app.config['SECRET_KEY'] = 'tonieflix-super-secret-key'
|
|
CORS(app, supports_credentials=True, allow_headers="*")
|
|
|
|
|
|
# ---------------------------------------------------------
|
|
# Toniecloud API & Playwright Hilfsfunktionen
|
|
# ---------------------------------------------------------
|
|
async def get_tonie_api_token(username: str, password: str) -> str | None:
|
|
"""Loggt sich automatisiert bei Tonies ein und gibt das Access-Token zurück."""
|
|
async with async_playwright() as p:
|
|
browser = await p.chromium.launch(headless=True)
|
|
context = await browser.new_context(viewport={'width': 1280, 'height': 800})
|
|
page = await context.new_page()
|
|
|
|
login_url = (
|
|
"https://login.tonies.com/auth/realms/tonies/protocol/openid-connect/auth?"
|
|
"client_id=my-tonies&redirect_uri=https%3A%2F%2Fmy.tonies.com%2Flogin%3Fredirect%3D%252F&"
|
|
"state=24115267-a4f0-4033-a2d4-bef68c83b07d&response_mode=fragment&"
|
|
"response_type=code&scope=openid&nonce=ee64d559-2b1c-4f4d-a01f-40d84c4dced1&"
|
|
"ui_locales=de&code_challenge=_lFACYXyUjTQEnb3JiqUWQ7xu4zA50xMNyXhhp3uUe8&"
|
|
"code_challenge_method=S256"
|
|
)
|
|
|
|
try:
|
|
await page.goto(login_url)
|
|
try:
|
|
await page.wait_for_selector("[data-testid='email-toggle']", timeout=5000)
|
|
await page.click("[data-testid='email-toggle']")
|
|
except Exception:
|
|
pass
|
|
|
|
await page.wait_for_timeout(1000)
|
|
await page.wait_for_selector("input[id='username'], input[name='username']", timeout=5000)
|
|
|
|
await page.type("input[id='username'], input[name='username']", username, delay=30)
|
|
await page.type("input[id='password'], input[name='password']", password, delay=30)
|
|
await page.click("input[type='submit'], button[type='submit']")
|
|
|
|
await page.wait_for_timeout(5000)
|
|
access_token = await page.evaluate("() => window.localStorage.getItem('authorization')")
|
|
await browser.close()
|
|
return access_token
|
|
except Exception as e:
|
|
print(f"Playwright Login-Fehler: {e}")
|
|
await browser.close()
|
|
return None
|
|
|
|
|
|
def get_household_id(access_token: str) -> str:
|
|
headers = {"Authorization": f"Bearer {access_token}", "Content-Type": "application/json", "User-Agent": "Mozilla/5.0"}
|
|
resp = requests.get("https://api.tonie.cloud/v2/households", headers=headers)
|
|
if resp.status_code != 200:
|
|
raise Exception(f"Fehler beim Laden der Haushalte: {resp.status_code} - {resp.text}")
|
|
households = resp.json()
|
|
household_list = households if isinstance(households, list) else households.get("households", [])
|
|
if not household_list:
|
|
raise Exception("Kein Haushalt gefunden.")
|
|
return household_list[0]["id"]
|
|
|
|
|
|
def get_creative_tonies(access_token: str, household_id: str) -> list[dict]:
|
|
headers = {"Authorization": f"Bearer {access_token}", "Content-Type": "application/json", "User-Agent": "Mozilla/5.0"}
|
|
resp = requests.get(f"https://api.tonie.cloud/v2/households/{household_id}/creativetonies", headers=headers)
|
|
if resp.status_code != 200:
|
|
raise Exception(f"Fehler beim Laden der Kreativ-Tonies: {resp.status_code} - {resp.text}")
|
|
raw_tonies = resp.json()
|
|
if isinstance(raw_tonies, dict):
|
|
raw_tonies = raw_tonies.get("creativeTonies", raw_tonies.get("items", []))
|
|
return [{"id": t.get("id"), "name": t.get("name"), "imageUrl": t.get("imageUrl")} for t in raw_tonies]
|
|
|
|
|
|
def upload_audio_to_creative_tonie(access_token: str, household_id: str, tonie_id: str, file_path: str, title: str, delete_all_chapters: bool):
|
|
headers = {"Authorization": f"Bearer {access_token}", "Content-Type": "application/json", "User-Agent": "Mozilla/5.0"}
|
|
|
|
# 1. S3 Berechtigung anfordern
|
|
upload_req_resp = requests.post("https://api.tonie.cloud/v2/file", json={"headers": {}}, headers=headers)
|
|
if upload_req_resp.status_code != 200:
|
|
raise Exception(f"Upload-Request fehlgeschlagen: {upload_req_resp.text}")
|
|
|
|
amazon_data = upload_req_resp.json()
|
|
s3_request = amazon_data.get("request", {})
|
|
fields = s3_request.get("fields", {})
|
|
file_id = amazon_data.get("fileId") or amazon_data.get("fileID") or amazon_data.get("file")
|
|
s3_url = s3_request.get("url", "https://bxn-toniecloud-prod-upload.s3.amazonaws.com/")
|
|
|
|
# 2. Datei zu S3 hochladen
|
|
if not Path(file_path).exists():
|
|
raise FileNotFoundError(f"Datei {file_path} nicht gefunden.")
|
|
|
|
multipart_fields = {
|
|
"key": fields.get("key"),
|
|
"x-amz-algorithm": fields.get("x-amz-algorithm"),
|
|
"x-amz-credential": fields.get("x-amz-credential"),
|
|
"x-amz-date": fields.get("x-amz-date"),
|
|
"policy": fields.get("policy"),
|
|
"x-amz-signature": fields.get("x-amz-signature"),
|
|
"x-amz-security-token": fields.get("x-amz-security-token"),
|
|
}
|
|
|
|
with open(file_path, "rb") as f:
|
|
files = {"file": (fields.get("key"), f, "audio/mpeg")}
|
|
s3_resp = requests.post(s3_url, data=multipart_fields, files=files)
|
|
|
|
if s3_resp.status_code not in (200, 204):
|
|
raise Exception(f"S3-Upload fehlgeschlagen: {s3_resp.text}")
|
|
|
|
# 3. Tonie-Details abrufen & Kapitel aktualisieren
|
|
tonie_detail_resp = requests.get(f"https://api.tonie.cloud/v2/households/{household_id}/creativetonies/{tonie_id}", headers=headers)
|
|
if tonie_detail_resp.status_code != 200:
|
|
raise Exception(f"Konnte Tonie-Details nicht abrufen: {tonie_detail_resp.text}")
|
|
|
|
tonie_data = tonie_detail_resp.json()
|
|
|
|
cleaned_chapters = []
|
|
if not delete_all_chapters:
|
|
for ch in tonie_data.get("chapters", []):
|
|
c_id = ch.get("id")
|
|
c_file = ch.get("file")
|
|
c_title = ch.get("title", "")
|
|
if isinstance(c_file, dict):
|
|
c_file = c_file.get("id") or c_file.get("file")
|
|
if c_id and c_file and str(c_file).lower() != "none":
|
|
cleaned_chapters.append({"id": str(c_id), "file": str(c_file), "title": str(c_title)})
|
|
|
|
# Neues Kapitel anhängen
|
|
cleaned_chapters.append({
|
|
"id": str(fields.get("key")),
|
|
"file": str(file_id),
|
|
"title": str(title)
|
|
})
|
|
|
|
update_payload = {
|
|
"name": tonie_data.get("name"),
|
|
"imageUrl": tonie_data.get("imageUrl"),
|
|
"chapters": cleaned_chapters
|
|
}
|
|
|
|
update_resp = requests.put(
|
|
f"https://api.tonie.cloud/v2/households/{household_id}/creativetonies/{tonie_id}",
|
|
json=update_payload,
|
|
headers=headers
|
|
)
|
|
|
|
if update_resp.status_code not in (200, 204):
|
|
raise Exception(f"Fehler beim Speichern der Kapitel: {update_resp.text}")
|
|
|
|
|
|
# ---------------------------------------------------------
|
|
# Bibliothek abrufen
|
|
# ---------------------------------------------------------
|
|
def get_books(single_book=None):
|
|
books = []
|
|
if os.path.exists(BASE_DIR):
|
|
items_to_check = [single_book] if single_book else sorted(os.listdir(BASE_DIR))
|
|
for item in items_to_check:
|
|
item_path = os.path.join(BASE_DIR, item)
|
|
if os.path.isdir(item_path):
|
|
files = os.listdir(item_path)
|
|
tracks = sorted([f for f in files if f.lower().endswith(('.mp3', '.ogg'))])
|
|
has_cover = any(f.lower() == 'cover.jpg' for f in files)
|
|
if tracks:
|
|
books.append({'name': item, 'tracks': tracks, 'has_cover': has_cover})
|
|
return books
|
|
|
|
|
|
# ---------------------------------------------------------
|
|
# HTML & JS Template (Frontend)
|
|
# ---------------------------------------------------------
|
|
TEMPLATE = """
|
|
<!DOCTYPE html>
|
|
<html lang="de">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Tonieflix</title>
|
|
<style>
|
|
:root { --primary: #e50914; --bg: #141414; --card: #1f1f1f; --text: #ffffff; }
|
|
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(--bg); color: var(--text); margin: 0; padding: 20px; padding-bottom: 160px; }
|
|
h1 { text-align: center; color: var(--primary); font-size: 3rem; margin-bottom: 10px; font-weight: 800; }
|
|
|
|
.top-controls { text-align: center; margin-bottom: 30px; display: flex; justify-content: center; gap: 15px; flex-wrap: wrap; }
|
|
input[type="text"] { padding: 12px 20px; width: 80%; max-width: 400px; border: 1px solid #333; background: #222; color: #fff; border-radius: 25px; font-size: 1rem; outline: none; }
|
|
input[type="text"]:focus { border-color: var(--primary); }
|
|
|
|
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; max-width: 1200px; margin: 0 auto; }
|
|
.card { background: var(--card); border-radius: 12px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.5); transition: transform 0.2s; display: flex; flex-direction: column; }
|
|
.card:hover { transform: scale(1.03); }
|
|
.card-clickable { cursor: pointer; flex-grow: 1; }
|
|
.card img { width: 100%; aspect-ratio: 1; object-fit: cover; background: #333; display: block; }
|
|
.card .title { padding: 12px 10px 5px 10px; text-align: center; font-weight: bold; font-size: 1rem; }
|
|
.card-actions { padding: 10px; text-align: center; display: flex; flex-direction: column; gap: 6px; }
|
|
.btn-direct, .btn-tonie { background: #333; color: #ccc; border: 1px solid #444; padding: 6px 14px; border-radius: 15px; font-size: 0.85rem; cursor: pointer; transition: 0.2s; }
|
|
.btn-direct:hover, .btn-tonie:hover { background: var(--primary); color: white; border-color: var(--primary); }
|
|
|
|
/* Player Bar */
|
|
.player-bar {
|
|
position: fixed; bottom: 20px; left: 15px; right: 15px;
|
|
background: #181818; border: 2px solid var(--primary); border-radius: 16px;
|
|
padding: 15px 20px; box-shadow: 0 -4px 20px rgba(0,0,0,0.8);
|
|
display: flex; flex-direction: column; align-items: center; gap: 12px; z-index: 1000;
|
|
}
|
|
.player-info { font-weight: bold; color: var(--primary); font-size: 1.1rem; text-align: center; }
|
|
.player-controls { display: flex; align-items: center; gap: 15px; width: 100%; max-width: 800px; justify-content: center; flex-wrap: wrap; }
|
|
audio { flex-grow: 1; min-width: 250px; outline: none; }
|
|
|
|
.btn { border: none; padding: 10px 15px; border-radius: 25px; cursor: pointer; font-size: 1rem; font-weight: bold; transition: opacity 0.2s; }
|
|
.btn:hover { opacity: 0.8; }
|
|
.btn:disabled { background: #444; color: #777; cursor: not-allowed; opacity: 1; }
|
|
.btn-nav { background: var(--primary); color: white; text-decoration: none; display: inline-block; }
|
|
.btn-dl { background: #2ed573; color: white; text-decoration: none; display: inline-block; }
|
|
|
|
.logout { position: absolute; top: 20px; right: 20px; color: #aaa; text-decoration: none; font-weight: bold; }
|
|
.logout:hover { color: #fff; }
|
|
|
|
/* Modal für Tonie-Upload */
|
|
#tonieModal {
|
|
display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
|
|
background: rgba(0,0,0,0.8); z-index: 2000; justify-content: center; align-items: center;
|
|
}
|
|
.modal-content {
|
|
background: #1f1f1f; padding: 30px; border-radius: 12px; width: 90%; max-width: 500px;
|
|
box-shadow: 0 5px 20px rgba(0,0,0,0.8); text-align: center; position: relative; max-height: 90vh; overflow-y: auto;
|
|
}
|
|
.modal-close { position: absolute; top: 15px; right: 15px; font-size: 1.5rem; cursor: pointer; color: #aaa; }
|
|
.modal-close:hover { color: #fff; }
|
|
.tonie-list { display: flex; flex-direction: column; gap: 10px; margin-top: 20px; text-align: left; }
|
|
.tonie-item {
|
|
display: flex; align-items: center; gap: 15px; background: #2a2a2a; padding: 10px; border-radius: 8px; cursor: pointer; transition: 0.2s;
|
|
}
|
|
.tonie-item:hover { background: #3a3a3a; border: 1px solid var(--primary); }
|
|
.tonie-item img { width: 50px; height: 50px; border-radius: 6px; object-fit: cover; }
|
|
.checkbox-container { margin: 15px 0; text-align: left; display: flex; align-items: center; gap: 10px; font-size: 0.9rem; }
|
|
|
|
#loadingOverlay {
|
|
display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
|
|
background: rgba(0,0,0,0.85); z-index: 3000; flex-direction: column; justify-content: center; align-items: center; color: white;
|
|
}
|
|
.spinner { border: 4px solid #333; border-top: 4px solid var(--primary); border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite; margin-bottom: 20px; }
|
|
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<a href="{{ url_for('logout') }}" class="logout">Abmelden</a>
|
|
<h1>🎬 Tonieflix</h1>
|
|
|
|
<div class="top-controls">
|
|
{% if single_mode %}
|
|
<a href="{{ url_for('index') }}" class="btn btn-nav" style="font-size: 1.1rem; padding: 12px 25px;">📚 Gesamte Bibliothek laden</a>
|
|
{% else %}
|
|
<input type="text" id="searchInput" placeholder="Hörbuch suchen...">
|
|
<a href="{{ url_for('tonie_login') }}" class="btn" style="background: #333; color: #fff; border: 1px solid #444;">🦊 Tonie-Login</a>
|
|
{% endif %}
|
|
</div>
|
|
|
|
<div class="grid" id="bookGrid">
|
|
{% for book in books %}
|
|
<div class="card" data-title="{{ book.name.lower() }}">
|
|
<div class="card-clickable" data-name="{{ book.name }}" data-tracks='{{ book.tracks|tojson }}'>
|
|
{% if book.has_cover %}
|
|
<img src="{{ url_for('serve_cover', book_name=book.name) }}" alt="Cover">
|
|
{% else %}
|
|
<img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' fill='%23333' viewBox='0 0 1 1'></svg>" alt="Kein Cover">
|
|
{% endif %}
|
|
<div class="title">{{ book.name }}</div>
|
|
</div>
|
|
<div class="card-actions">
|
|
<button class="btn-direct" data-name="{{ book.name }}">🔗 Direktlink</button>
|
|
<button class="btn-tonie" data-name="{{ book.name }}">🦊 Auf Tonie</button>
|
|
</div>
|
|
</div>
|
|
{% else %}
|
|
<p style="text-align: center; width: 100%; color: #aaa;">Keine Hörbücher gefunden.</p>
|
|
{% endfor %}
|
|
</div>
|
|
|
|
<!-- Tonie Auswahl Modal -->
|
|
<div id="tonieModal">
|
|
<div class="modal-content">
|
|
<span class="modal-close" onclick="closeTonieModal()">×</span>
|
|
<h2 style="color: var(--primary); margin-top: 0;">Kreativ-Tonie auswählen</h2>
|
|
<p id="modalBookTitle" style="color: #aaa; font-size: 0.9rem;"></p>
|
|
|
|
<div class="checkbox-container">
|
|
<input type="checkbox" id="deleteAllChapters" style="transform: scale(1.2);">
|
|
<label for="deleteAllChapters">Vorhandene Kapitel auf dem Tonie löschen</label>
|
|
</div>
|
|
|
|
<div class="tonie-list" id="tonieListContainer">
|
|
<p style="text-align: center; color: #aaa;">Lade Kreativ-Tonies...</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Ladebildschirm Upload -->
|
|
<div id="loadingOverlay">
|
|
<div class="spinner"></div>
|
|
<h2 id="loadingText">Lade Hörbuch auf Kreativ-Tonie hoch...</h2>
|
|
<p style="color: #aaa;">Bitte Fenster nicht schließen.</p>
|
|
</div>
|
|
|
|
<!-- Player Bar -->
|
|
<div class="player-bar" id="playerBar" style="display: none;">
|
|
<div class="player-info" id="playerInfo">Wird geladen...</div>
|
|
<div class="player-controls">
|
|
<button class="btn btn-nav" id="prevBtn">⏮</button>
|
|
<audio id="audioPlayer" controls></audio>
|
|
<button class="btn btn-nav" id="nextBtn">⏭</button>
|
|
<a href="#" class="btn btn-dl" id="downloadBtn">⬇️ ZIP</a>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
const audioPlayer = document.getElementById('audioPlayer');
|
|
const playerBar = document.getElementById('playerBar');
|
|
const playerInfo = document.getElementById('playerInfo');
|
|
const searchInput = document.getElementById('searchInput');
|
|
const cards = document.querySelectorAll('.card');
|
|
|
|
const prevBtn = document.getElementById('prevBtn');
|
|
const nextBtn = document.getElementById('nextBtn');
|
|
const downloadBtn = document.getElementById('downloadBtn');
|
|
|
|
const tonieModal = document.getElementById('tonieModal');
|
|
const modalBookTitle = document.getElementById('modalBookTitle');
|
|
const tonieListContainer = document.getElementById('tonieListContainer');
|
|
const loadingOverlay = document.getElementById('loadingOverlay');
|
|
const loadingText = document.getElementById('loadingText');
|
|
|
|
let selectedBookNameForTonie = '';
|
|
|
|
// Suche
|
|
if (searchInput) {
|
|
searchInput.addEventListener('input', (e) => {
|
|
const term = e.target.value.toLowerCase();
|
|
cards.forEach(card => {
|
|
const title = card.getAttribute('data-title');
|
|
card.style.display = title.includes(term) ? 'flex' : 'none';
|
|
});
|
|
});
|
|
}
|
|
|
|
// Event-Listener für Karten
|
|
document.querySelectorAll('.card-clickable').forEach(el => {
|
|
el.addEventListener('click', () => {
|
|
const name = el.getAttribute('data-name');
|
|
const tracks = JSON.parse(el.getAttribute('data-tracks'));
|
|
startBook(name, tracks);
|
|
});
|
|
});
|
|
|
|
document.querySelectorAll('.btn-direct').forEach(btn => {
|
|
btn.addEventListener('click', (e) => {
|
|
e.stopPropagation();
|
|
copyDirectLink(btn.getAttribute('data-name'));
|
|
});
|
|
});
|
|
|
|
document.querySelectorAll('.btn-tonie').forEach(btn => {
|
|
btn.addEventListener('click', (e) => {
|
|
e.stopPropagation();
|
|
selectedBookNameForTonie = btn.getAttribute('data-name');
|
|
openTonieModal(selectedBookNameForTonie);
|
|
});
|
|
});
|
|
|
|
function openTonieModal(bookName) {
|
|
modalBookTitle.innerText = `Hörbuch: "${bookName}"`;
|
|
tonieModal.style.display = 'flex';
|
|
tonieListContainer.innerHTML = '<p style="text-align: center; color: #aaa;">Lade Kreativ-Tonies...</p>';
|
|
|
|
fetch('/api/tonies')
|
|
.then(res => res.json())
|
|
.then(data => {
|
|
if (data.error) {
|
|
tonieListContainer.innerHTML = `<p style="color: var(--primary); text-align: center;">${data.error} <br><a href="/tonie-login" style="color: #fff;">Hier einloggen</a></p>`;
|
|
return;
|
|
}
|
|
if (data.length === 0) {
|
|
tonieListContainer.innerHTML = '<p style="text-align: center; color: #aaa;">Keine Kreativ-Tonies gefunden.</p>';
|
|
return;
|
|
}
|
|
let html = '';
|
|
data.forEach(t => {
|
|
html += `
|
|
<div class="tonie-item" onclick="uploadToTonie('${t.id}')">
|
|
<img src="${t.imageUrl || 'https://via.placeholder.com/50'}" alt="Tonie">
|
|
<div>
|
|
<div style="font-weight: bold;">${t.name}</div>
|
|
<div style="font-size: 0.75rem; color: #888;">ID: ${t.id}</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
});
|
|
tonieListContainer.innerHTML = html;
|
|
})
|
|
.catch(err => {
|
|
tonieListContainer.innerHTML = '<p style="color: red; text-align: center;">Fehler beim Laden der Tonies.</p>';
|
|
});
|
|
}
|
|
|
|
function closeTonieModal() {
|
|
tonieModal.style.display = 'none';
|
|
}
|
|
|
|
function uploadToTonie(tonieId) {
|
|
const deleteAll = document.getElementById('deleteAllChapters').checked;
|
|
closeTonieModal();
|
|
loadingOverlay.style.display = 'flex';
|
|
loadingText.innerText = `Lade "${selectedBookNameForTonie}" auf den Kreativ-Tonie...`;
|
|
|
|
fetch('/api/upload-to-tonie', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ book_name: selectedBookNameForTonie, tonie_id: tonieId, delete_all: deleteAll })
|
|
})
|
|
.then(res => res.json())
|
|
.then(data => {
|
|
loadingOverlay.style.display = 'none';
|
|
if (data.success) {
|
|
alert('Hörbuch erfolgreich auf den Kreativ-Tonie geladen! 🎉');
|
|
} else {
|
|
alert('Fehler beim Upload: ' + (data.error || 'Unbekannter Fehler'));
|
|
}
|
|
})
|
|
.catch(err => {
|
|
loadingOverlay.style.display = 'none';
|
|
alert('Netzwerkfehler beim Upload.');
|
|
});
|
|
}
|
|
|
|
prevBtn.addEventListener('click', () => { if (currentBookState.trackIndex > 0) { currentBookState.trackIndex--; loadTrackInfo(true); } });
|
|
nextBtn.addEventListener('click', () => { if (currentBookState.trackIndex < currentBookState.tracks.length - 1) { currentBookState.trackIndex++; loadTrackInfo(true); } });
|
|
|
|
function copyDirectLink(bookName) {
|
|
const url = window.location.origin + '/play/' + encodeURIComponent(bookName);
|
|
navigator.clipboard?.writeText(url).then(() => alert('Direktlink kopiert!')).catch(() => prompt('Direktlink:', url));
|
|
}
|
|
|
|
let currentBookState = { bookName: '', tracks: [], trackIndex: 0 };
|
|
function startBook(bookName, tracks) {
|
|
if (!tracks || tracks.length === 0) return;
|
|
currentBookState = { bookName: bookName, tracks: tracks, trackIndex: 0 };
|
|
playerBar.style.display = 'flex';
|
|
loadTrackInfo(true);
|
|
}
|
|
|
|
function loadTrackInfo(autoPlay) {
|
|
const track = currentBookState.tracks[currentBookState.trackIndex];
|
|
audioPlayer.src = `/stream/${encodeURIComponent(currentBookState.bookName)}/${encodeURIComponent(track)}`;
|
|
playerInfo.innerText = `${currentBookState.bookName} (Kapitel ${currentBookState.trackIndex + 1} von ${currentBookState.tracks.length})`;
|
|
prevBtn.disabled = currentBookState.trackIndex === 0;
|
|
nextBtn.disabled = currentBookState.trackIndex === currentBookState.tracks.length - 1;
|
|
downloadBtn.href = `/download/${encodeURIComponent(currentBookState.bookName)}`;
|
|
if (autoPlay) audioPlayer.play().catch(e => console.warn(e));
|
|
}
|
|
|
|
audioPlayer.addEventListener('ended', () => {
|
|
if (currentBookState.trackIndex < currentBookState.tracks.length - 1) {
|
|
currentBookState.trackIndex++;
|
|
loadTrackInfo(true);
|
|
}
|
|
});
|
|
</script>
|
|
</body>
|
|
</html>
|
|
"""
|
|
|
|
LOGIN_TEMPLATE = """
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Login - Tonieflix</title>
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<style>
|
|
body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #141414; color: #fff; margin: 0; }
|
|
.login-box { background: #1f1f1f; padding: 40px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.8); text-align: center; width: 100%; max-width: 320px; }
|
|
input { padding: 12px; margin: 10px 0; border: 1px solid #333; background: #2b2b2b; color: #fff; border-radius: 5px; width: 100%; box-sizing: border-box;}
|
|
button { background: #e50914; color: white; border: none; padding: 12px 20px; border-radius: 5px; cursor: pointer; width: 100%; font-size: 1rem; font-weight: bold; }
|
|
button:hover { opacity: 0.9; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="login-box">
|
|
<h2 style="color: #e50914; margin-top: 0;">🎬 Tonieflix</h2>
|
|
<form method="POST">
|
|
<input type="password" name="password" placeholder="App-Passwort" required autofocus>
|
|
<button type="submit">Eintreten</button>
|
|
</form>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
"""
|
|
|
|
TONIE_LOGIN_TEMPLATE = """
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>Tonie-Login - Tonieflix</title>
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<style>
|
|
body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #141414; color: #fff; margin: 0; }
|
|
.login-box { background: #1f1f1f; padding: 40px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.8); text-align: center; width: 100%; max-width: 350px; }
|
|
input { padding: 12px; margin: 10px 0; border: 1px solid #333; background: #2b2b2b; color: #fff; border-radius: 5px; width: 100%; box-sizing: border-box;}
|
|
button { background: #e50914; color: white; border: none; padding: 12px 20px; border-radius: 5px; cursor: pointer; width: 100%; font-size: 1rem; font-weight: bold; }
|
|
button:hover { opacity: 0.9; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="login-box">
|
|
<h2 style="color: #e50914; margin-top: 0;">🦊 Tonies Account</h2>
|
|
<p style="font-size: 0.85rem; color: #aaa;">Gib deine Zugangsdaten für my.tonies.com ein:</p>
|
|
<form method="POST">
|
|
<input type="email" name="tonie_email" placeholder="E-Mail-Adresse" required>
|
|
<input type="password" name="tonie_password" placeholder="Passwort" required>
|
|
<button type="submit">Token generieren & Einloggen</button>
|
|
</form>
|
|
{% if error %}
|
|
<p style="color: var(--primary); font-size: 0.9rem; margin-top: 15px;">{{ error }}</p>
|
|
{% endif %}
|
|
</div>
|
|
</body>
|
|
</html>
|
|
"""
|
|
|
|
# ---------------------------------------------------------
|
|
# Flask Routen
|
|
# ---------------------------------------------------------
|
|
@app.before_request
|
|
def require_login():
|
|
if request.method == 'OPTIONS' or request.path.startswith('/api/books'):
|
|
return None
|
|
if request.args.get('pw') == PASSWORD:
|
|
return None
|
|
if request.endpoint not in ['login', 'static'] and not session.get('logged_in'):
|
|
return redirect(url_for('login', next=request.full_path if request.full_path != '/' else None))
|
|
|
|
@app.route('/login', methods=['GET', 'POST'])
|
|
def login():
|
|
next_url = request.args.get('next') or url_for('index')
|
|
if request.method == 'POST':
|
|
if request.form.get('password') == PASSWORD:
|
|
session['logged_in'] = True
|
|
return redirect(next_url)
|
|
else:
|
|
return "Falsches Passwort!", 403
|
|
return render_template_string(LOGIN_TEMPLATE)
|
|
|
|
@app.route('/tonie-login', methods=['GET', 'POST'])
|
|
def tonie_login():
|
|
error = None
|
|
if request.method == 'POST':
|
|
email = request.form.get('tonie_email')
|
|
pwd = request.form.get('tonie_password')
|
|
# Playwright Token holen (Asynchroner Aufruf im Sync Flask)
|
|
token = asyncio.run(get_tonie_api_token(email, pwd))
|
|
if token:
|
|
session['tonie_token'] = token
|
|
return redirect(url_for('index'))
|
|
else:
|
|
error = "Login fehlgeschlagen. Bitte Zugangsdaten prüfen."
|
|
return render_template_string(TONIE_LOGIN_TEMPLATE, error=error)
|
|
|
|
@app.route('/logout')
|
|
def logout():
|
|
session.clear()
|
|
return redirect(url_for('login'))
|
|
|
|
@app.route('/')
|
|
def index():
|
|
return render_template_string(TEMPLATE, books=get_books(), auto_play="", single_mode=False)
|
|
|
|
@app.route('/play/<path:book_name>')
|
|
def play_book(book_name):
|
|
return render_template_string(TEMPLATE, books=get_books(single_book=book_name), auto_play=book_name, single_mode=True)
|
|
|
|
@app.route('/cover/<path:book_name>')
|
|
def serve_cover(book_name):
|
|
return send_from_directory(os.path.join(BASE_DIR, book_name), 'cover.jpg')
|
|
|
|
@app.route('/stream/<path:book_name>/<path:track_name>')
|
|
def serve_audio(book_name, track_name):
|
|
return send_from_directory(os.path.join(BASE_DIR, book_name), track_name)
|
|
|
|
@app.route('/download/<path:book_name>')
|
|
def download_book(book_name):
|
|
book_path = os.path.join(BASE_DIR, book_name)
|
|
if not os.path.isdir(book_path):
|
|
return "Hörbuch nicht gefunden", 404
|
|
memory_file = io.BytesIO()
|
|
with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_STORED) as zf:
|
|
for root, dirs, files in os.walk(book_path):
|
|
for file in files:
|
|
zf.write(os.path.join(root, file), arcname=file)
|
|
memory_file.seek(0)
|
|
return send_file(memory_file, download_name=f"{book_name}.zip", as_attachment=True, mimetype='application/zip')
|
|
|
|
# --- API Endpunkte für Tonies ---
|
|
@app.route('/api/tonies')
|
|
def api_tonies():
|
|
token = session.get('tonie_token')
|
|
if not token:
|
|
return jsonify({"error": "Nicht bei Tonies eingeloggt."}), 401
|
|
try:
|
|
household_id = get_household_id(token)
|
|
tonies = get_creative_tonies(token, household_id)
|
|
return jsonify(tonies)
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
@app.route('/api/upload-to-tonie', methods=['POST'])
|
|
def api_upload_to_tonie():
|
|
token = session.get('tonie_token')
|
|
if not token:
|
|
return jsonify({"success": False, "error": "Nicht eingeloggt."}), 401
|
|
|
|
data = request.json
|
|
book_name = data.get('book_name')
|
|
tonie_id = data.get('tonie_id')
|
|
delete_all = data.get('delete_all', False)
|
|
|
|
if not book_name or not tonie_id:
|
|
return jsonify({"success": False, "error": "Fehlende Parameter."}), 400
|
|
|
|
try:
|
|
household_id = get_household_id(token)
|
|
book_path = os.path.join(BASE_DIR, book_name)
|
|
|
|
if not os.path.isdir(book_path):
|
|
return jsonify({"success": False, "error": "Hörbuch-Ordner nicht gefunden."}), 404
|
|
|
|
files = sorted([f for f in os.listdir(book_path) if f.lower().endswith(('.mp3', '.ogg'))])
|
|
if not files:
|
|
return jsonify({"success": False, "error": "Keine Audiospuren im Hörbuch gefunden."}), 400
|
|
|
|
# Jede Spur nacheinander hochladen
|
|
for index, track in enumerate(files):
|
|
file_path = os.path.join(book_path, track)
|
|
# Titel des Kapitels (Dateiname ohne Endung oder schöner Name)
|
|
title = os.path.splitext(track)[0]
|
|
|
|
# Beim ersten Track wird ggf. der 'delete_all_chapters' Schalter angewendet, danach hängen wir an
|
|
should_delete = delete_all if index == 0 else False
|
|
|
|
upload_audio_to_creative_tonie(
|
|
access_token=token,
|
|
household_id=household_id,
|
|
tonie_id=tonie_id,
|
|
file_path=file_path,
|
|
title=title,
|
|
delete_all_chapters=should_delete
|
|
)
|
|
|
|
return jsonify({"success": True})
|
|
except Exception as e:
|
|
return jsonify({"success": False, "error": str(e)}), 500
|
|
|
|
|
|
if __name__ == '__main__':
|
|
app.run(host='0.0.0.0', port=5005) |