feat: save guesses and show in admin page
This commit is contained in:
1 parent
023152d417
commit
43185dee64
10 files changed
+414
-47
No files matched your search
@@ -1,26 +1,28 @@
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify
|
||||
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
|
||||
|
||||
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("songs.json", encoding="utf-8") as f:
|
||||
with open(BASE_DIR / "data" / "songs.json", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
def load_results_list():
|
||||
with open("results.json", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
def write_results_list(results):
|
||||
with open("results.json", mode="w", encoding="utf-8") as f:
|
||||
json.dump(results, f, ensure_ascii=False, indent=2)
|
||||
|
||||
@bp.route("/login")
|
||||
def login():
|
||||
if "name" in session:
|
||||
@@ -31,12 +33,19 @@ def login():
|
||||
@bp.route("/", methods=["GET", "POST"])
|
||||
def index():
|
||||
if request.method == "POST":
|
||||
session["name"] = request.form["name"].strip()
|
||||
if "name" not in session:
|
||||
name = request.form.get("name", "").strip()[:60]
|
||||
if not name:
|
||||
return redirect(url_for("main.login"))
|
||||
session.clear() # neuer Teilnehmer = frischer Stand
|
||||
session["name"] = name
|
||||
session["pid"] = create_participant(name)
|
||||
return redirect(url_for("main.test"))
|
||||
if "pid" not in session:
|
||||
return redirect(url_for("main.login"))
|
||||
return render_template("index.html")
|
||||
|
||||
|
||||
|
||||
@bp.route("/test")
|
||||
def test():
|
||||
if "name" not in session:
|
||||
@@ -79,41 +88,150 @@ def api_getRandomSong():
|
||||
|
||||
@bp.route("/api/rate", methods=["POST"])
|
||||
def api_rate():
|
||||
if "name" not in session or "current" not in session:
|
||||
if "pid" not in session or "current" not in session:
|
||||
return jsonify({"error": "no session detected"}), 401
|
||||
|
||||
|
||||
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
|
||||
|
||||
song_id = session["current"]["id"]
|
||||
solution = session["current"]["truth"]
|
||||
name = session["name"]
|
||||
|
||||
results = load_results_list()
|
||||
|
||||
person = next((p for p in results if p["name"] == name), None)
|
||||
|
||||
if person is None: # create person if not created yet
|
||||
results.append({
|
||||
"name": name,
|
||||
"guesses": [{
|
||||
"song_id": song_id,
|
||||
"right": choice == solution
|
||||
}]
|
||||
})
|
||||
else:
|
||||
person["guesses"].append({
|
||||
"song_id": song_id,
|
||||
"right": choice == solution
|
||||
})
|
||||
|
||||
write_results_list(results)
|
||||
|
||||
|
||||
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", [])
|
||||
done.append(song_id)
|
||||
if cur["id"] not in done:
|
||||
done.append(cur["id"])
|
||||
session["done"] = done
|
||||
session.pop("current", None)
|
||||
|
||||
|
||||
return jsonify({"saved": True})
|
||||
|
||||
|
||||
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"))
|
||||
Reference in new issue
Block a user