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 = """
Keine Hörbücher gefunden.
{% endfor %}Bitte Fenster nicht schließen.
Gib deine Zugangsdaten für my.tonies.com ein:
{% if error %}{{ error }}
{% endif %}