341 lines
11 KiB
Python
341 lines
11 KiB
Python
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
|
||
|
||
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():
|
||
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"))
|
||
|
||
@bp.route("/admin/add")
|
||
@admin_required
|
||
def admin_add():
|
||
return render_template("admin_add.html")
|
||
|
||
@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)
|
||
|
||
#stem = os.path.splitext(filename_new)[0]
|
||
song = add_song({
|
||
"name": title,
|
||
"artist": artist,
|
||
"original": {"filename": filename_new},
|
||
"edits": [],
|
||
})
|
||
|
||
return jsonify({"saved": True, "filename": filename_new}) |