from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify, Response, current_app, abort import json from werkzeug.utils import secure_filename from pathlib import Path import random import csv import hmac import io import os import time import re import uuid from functools import wraps from db import init_db, get_db, close_db, create_participant, now from datetime import datetime, timezone import threading from mutagen import File import subprocess bp = Blueprint("main", __name__) init_db() bp.teardown_app_request(close_db) BASE_DIR = Path(__file__).parent BASE_MUSIC_DIR = BASE_DIR / "static" / "data" / "music" BASE_MUSIC_FILENAME_DIR = "data/music/" SONGS_PATH = BASE_DIR / "data" / "songs.json" _songs_lock = threading.Lock() def load_songs_list(): with open(SONGS_PATH, encoding="utf-8") as f: return json.load(f) def save_songs_list(songs): tmp = SONGS_PATH.with_suffix(".json.tmp") with open(tmp, "w", encoding="utf-8") as f: json.dump(songs, f, ensure_ascii=False, indent=2) os.replace(tmp, SONGS_PATH) # atomar ersetzen def next_song_id(songs, prefix="", width=3): nums = [] for s in songs: m = re.fullmatch(rf"{prefix}(\d+)", str(s["id"])) if m: nums.append(int(m.group(1))) return f"{prefix}{max(nums, default=0) + 1:0{width}d}" def add_song(song): with _songs_lock: songs = load_songs_list() song["id"] = next_song_id(songs) songs.append(song) save_songs_list(songs) return song ALLOWED_EXTENSIONS = {"mp3", "wav", "flac", "ogg", "m4a"} def allowed_file(filename): return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS def session_required(api=False, participant=True): """Prüft Datenschutz-Zustimmung und (optional) angelegten Teilnehmer. api=True -> JSON-Fehler statt Redirect participant=False -> nur Datenschutz prüfen (z. B. für die Namenseingabe) """ def decorator(view): @wraps(view) def wrapper(*args, **kwargs): if "dse_agreed" not in session: if api: return jsonify({"error": "privacy policy not accepted"}), 403 return redirect(url_for("main.datenschutz")) if participant and "pid" not in session: if api: return jsonify({"error": "no session detected"}), 401 return redirect(url_for("main.login")) return view(*args, **kwargs) return wrapper return decorator @bp.route("/datenschutz") def datenschutz(): return render_template("datenschutz.html") @bp.route("/agree-dse", methods=["POST"]) def agree_dse(): session["dse_agreed"] = True session["dse_agreed_at"] = datetime.now(timezone.utc).isoformat() return redirect(url_for("main.index")) @bp.route("/login") @session_required(participant=False) def login(): if "pid" in session: return redirect(url_for("main.index")) return render_template("login.html") @bp.route("/start", methods=["POST"]) @session_required(participant=False) def start(): name = request.form.get("name", "").strip()[:60] if not name: return redirect(url_for("main.login")) dse_at = session.get("dse_agreed_at") session.clear() session["dse_agreed"] = True session["dse_agreed_at"] = dse_at session["name"] = name session["pid"] = create_participant(name) return redirect(url_for("main.index")) @bp.route("/") @session_required() def index(): return render_template("index.html") @bp.route("/test") @session_required() def test(): return render_template("test.html", name=session["name"]) @bp.route("/api/getRandomSong") @session_required(api=True) def api_getRandomSong(): done = session.get("done", []) #print(done) remaining = [s for s in load_songs_list() if s["id"] not in done] #print(remaining) if not remaining: return jsonify({"finished": True}) song = remaining[0] truth = random.choice(["a", "b"]) session["current"] = {"id": song["id"], "truth": truth} truth_path = BASE_MUSIC_FILENAME_DIR + song["original"]["filename"] random_lie_path = BASE_MUSIC_FILENAME_DIR + random.choice(song["edits"])["filename"] if truth == "a": path_a = truth_path path_b = random_lie_path else: path_a = random_lie_path path_b = truth_path return jsonify({ "finished": False, "a": url_for("static", filename=path_a), "b": url_for("static", filename=path_b), "number": len(done) + 1, "song_name": song["name"], }) @bp.route("/api/rate", methods=["POST"]) @session_required(api=True) def api_rate(): data = request.get_json(silent=True) or {} choice = data.get("choice") if choice == "gleich": # beide Schreibweisen akzeptieren choice = "non" if choice not in ("a", "b", "non"): return jsonify({"error": "invalid choice"}), 400 cur = session["current"] db = get_db() with db: # eine Transaktion, wird automatisch committet db.execute( """INSERT OR IGNORE INTO ratings (participant_id, song_id, choice, truth, original_chosen, edit, created) VALUES (?, ?, ?, ?, ?, ?, ?)""", (session["pid"], cur["id"], choice, cur["truth"], int(choice == cur["truth"]), cur.get("edit"), now())) done = session.get("done", []) if cur["id"] not in done: done.append(cur["id"]) session["done"] = done session.pop("current", None) truth = cur["truth"] if not current_app.debug: truth = False return jsonify({"saved": True, "solution": {"truth": truth, "choice": choice}}) def admin_required(view): @wraps(view) def wrapper(*args, **kwargs): if not session.get("admin"): return redirect(url_for("main.admin_login")) return view(*args, **kwargs) return wrapper @bp.route("/admin/login", methods=["GET", "POST"]) def admin_login(): error = None if request.method == "POST": # Erst zur Anfragezeit lesen, damit load_dotenv() aus main.py schon gelaufen ist expected = os.environ.get("ADMIN_PASSWORD", "") given = request.form.get("password", "") if not expected: error = "Es ist kein Admin-Passwort konfiguriert (.env)." elif hmac.compare_digest(given.encode(), expected.encode()): session["admin"] = True return redirect(url_for("main.admin")) else: time.sleep(1) # bremst automatisches Durchprobieren error = "Falsches Passwort." return render_template("admin_login.html", error=error) @bp.route("/admin/logout", methods=["POST"]) def admin_logout(): session.pop("admin", None) return redirect(url_for("main.admin_login")) CHOICE_LABELS = {"a": "A", "b": "B", "non": "Kein Unterschied"} @bp.route("/admin") @admin_required def admin(): return render_template("admin.html") def csv_safe(value): """Verhindert, dass Calc/Excel einen Namen wie '=1+1' als Formel ausführt.""" s = str(value) return "'" + s if s[:1] in ("=", "+", "-", "@") else s @bp.route("/admin/export.csv") @admin_required def admin_export(): songs = {s["id"]: s["name"] for s in load_songs_list()} out = io.StringIO() w = csv.writer(out, delimiter=";") w.writerow(["Name", "Gestartet", "Song-ID", "Song", "Original gewählt", "Wahl", "Position Original", "Bearbeitung"]) query = """SELECT p.name, p.created AS started, r.song_id, r.original_chosen, r.choice, r.truth, r.edit FROM ratings r JOIN participants p ON p.id = r.participant_id ORDER BY p.created, r.id""" for r in get_db().execute(query): w.writerow([ csv_safe(r["name"]), r["started"], r["song_id"], csv_safe(songs.get(r["song_id"], "")), "ja" if r["original_chosen"] else "nein", CHOICE_LABELS.get(r["choice"], r["choice"]), r["truth"].upper(), r["edit"] or "", ]) return Response("\ufeff" + out.getvalue(), mimetype="text/csv", headers={"Content-Disposition": "attachment; filename=ergebnisse.csv"}) @bp.route("/debug/reset", methods=["POST"]) def debug_reset(): if not current_app.debug: abort(404) # im normalen Betrieb existiert die Route praktisch nicht session.clear() return redirect(url_for("main.login")) @bp.route("/admin/add") @admin_required def admin_add(): return render_template("admin_add.html") @bp.route("/admin/results") @admin_required def admin_results(): db = get_db() songs = {s["id"]: s["name"] for s in load_songs_list()} by_person = {} for r in db.execute("SELECT * FROM ratings ORDER BY id"): by_person.setdefault(r["participant_id"], []).append({ "song_id": r["song_id"], "right": bool(r["original_chosen"]), "choice": CHOICE_LABELS.get(r["choice"], r["choice"]), "edit": r["edit"] or "–", }) rows = [] for p in db.execute("SELECT id, name, created FROM participants ORDER BY created DESC"): guesses = by_person.get(p["id"], []) if not guesses: continue # nur Teilnehmer mit mindestens einer Bewertung total = len(guesses) right = sum(g["right"] for g in guesses) rows.append({ "name": p["name"], "started": p["created"], "total": total, "right": right, "quote": round(100 * right / total), "guesses": guesses, }) total_all = sum(r["total"] for r in rows) right_all = sum(r["right"] for r in rows) stats = { "people": len(rows), "guesses": total_all, "quote": round(100 * right_all / total_all) if total_all else None, } return render_template("admin_results.html", rows=rows, stats=stats, songs=songs) @bp.route("/admin/list") @admin_required def admin_list(): songs = load_songs_list() return render_template("admin_tasksList.html", songs=songs) @bp.route("/admin/add/") @admin_required def admin_add_task(songId): song = False for s in load_songs_list(): if s["id"] == songId: song = s if not song: return 404 return render_template("admin_add_task.html", song=song) @bp.route("/api/admin/add", methods=["POST"]) @admin_required def api_admin_add(): title = request.form.get("title", "").strip() artist = request.form.get("artist", "").strip() file = request.files.get("file") if not title: return jsonify({"saved": False, "error": "Titel fehlt"}), 400 if not file or file.filename == "": return jsonify({"saved": False, "error": "Keine Datei"}), 400 if not allowed_file(file.filename): return jsonify({"saved": False, "error": "Dateityp nicht erlaubt"}), 400 ext = os.path.splitext(secure_filename(file.filename))[1].lower() filename_new = uuid.uuid4().hex + ext BASE_MUSIC_DIR.mkdir(parents=True, exist_ok=True) file.save(BASE_MUSIC_DIR / filename_new) # read bitrate and sampling rate audio = File(BASE_MUSIC_DIR / filename_new) #stem = os.path.splitext(filename_new)[0] song = add_song({ "name": title, "artist": artist, "original": { "filename": filename_new, "sampling_rate": audio.info.sample_rate, "bitrate": audio.info.bitrate }, "edits": [], }) return jsonify({"saved": True, "filename": filename_new}) VALID_SAMPLING_RATES = {8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000} @bp.route("/api/admin/add/", methods=["POST"]) @admin_required def api_admin_add_task(songId): mode = request.form.get("mode", "cbr") sampling_rate = request.form.get("sampling_rate", type=int) if mode not in ("cbr", "vbr"): return jsonify({"saved": False, "error": "Ungültiger Modus"}), 400 if sampling_rate not in VALID_SAMPLING_RATES: return jsonify({"saved": False, "error": "Ungültige Abtastrate"}), 400 songs = load_songs_list() song = next((s for s in songs if str(s["id"]) == songId), None) if song is None: return jsonify({"saved": False, "error": "Song nicht gefunden"}), 404 original = song["original"] if sampling_rate > original["sampling_rate"]: return jsonify({"saved": False, "error": "Abtastrate höher als Original"}), 400 if mode == "vbr": quality = request.form.get("quality", type=int) if quality is None or not 0 <= quality <= 9: return jsonify({"saved": False, "error": "Ungültige VBR-Qualität"}), 400 quality_args = ["-q:a", str(quality)] else: bitrate_kbps = request.form.get("bitrate", type=int) if not bitrate_kbps or bitrate_kbps <= 0: return jsonify({"saved": False, "error": "Bitrate fehlt"}), 400 if bitrate_kbps * 1000 > original["bitrate"] + 1000: return jsonify({"saved": False, "error": "Bitrate höher als Original"}), 400 quality_args = ["-b:a", f"{bitrate_kbps}k"] src = BASE_MUSIC_DIR / original["filename"] if not src.is_file(): return jsonify({"saved": False, "error": "Originaldatei fehlt"}), 404 edit_id = uuid.uuid4().hex dst = BASE_MUSIC_DIR / (edit_id + ".mp3") # immer MP3, siehe Hinweis unten try: subprocess.run( ["ffmpeg", "-y", "-i", str(src), "-vn", "-c:a", "libmp3lame", *quality_args, "-ar", str(sampling_rate), str(dst)], check=True, capture_output=True, timeout=300, ) except subprocess.CalledProcessError as e: dst.unlink(missing_ok=True) current_app.logger.error("ffmpeg: %s", e.stderr.decode(errors="replace")[-1000:]) return jsonify({"saved": False, "error": "Konvertierung fehlgeschlagen"}), 500 except subprocess.TimeoutExpired: dst.unlink(missing_ok=True) return jsonify({"saved": False, "error": "Zeitüberschreitung"}), 500 # tatsächliche Werte aus der fertigen Datei lesen out = File(dst) actual_bitrate = out.info.bitrate if out else None actual_rate = out.info.sample_rate if out else sampling_rate song.setdefault("edits", []).append({ "id": edit_id, "filename": dst.name, "mode": mode, "quality": quality if mode == "vbr" else None, "bitrate": actual_bitrate, "sampling_rate": actual_rate, }) save_songs_list(songs) return jsonify({"saved": True, "id": edit_id})