Files
AudioRating/routes.py
T
2026-11-05 14:44:51 +01:00

273 lines
8.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify, Response, current_app, abort
import json
from pathlib import Path
import random
import csv
import hmac
import io
import os
import time
from functools import wraps
from db import init_db, get_db, close_db, create_participant, now
from datetime import datetime, timezone
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/"
def load_songs_list():
with open(BASE_DIR / "data" / "songs.json", encoding="utf-8") as f:
return json.load(f)
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"] + ".mp3"
random_lie_path = BASE_MUSIC_FILENAME_DIR + random.choice(song["edits"])["filename"] + ".mp3"
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():
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.html", rows=rows, stats=stats, songs=songs)
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"))