Compare commits

..
2 Commits
Author SHA1 Message Date
robin 29ebab923d feat: admin: create subtask and upload file 2026-11-05 15:49:35 +01:00
robin 36196a736a feat: add admin_add 2026-11-05 14:57:41 +01:00
6 changed files with 169 additions and 29 deletions

No files matched your search

-28
View File
@@ -1,28 +0,0 @@
[
{
"name": "r",
"guesses": [
{
"song_id": "001",
"right": true
},
{
"song_id": "002",
"right": false
}
]
},
{
"name": "Robin",
"guesses": [
{
"song_id": "001",
"right": false
},
{
"song_id": "002",
"right": false
}
]
}
]
+1
View File
@@ -8,6 +8,7 @@ load_dotenv()
app = Flask(__name__) app = Flask(__name__)
app.secret_key = os.environ["SECRET_KEY"] app.secret_key = os.environ["SECRET_KEY"]
app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024 # 50 MB
app.register_blueprint(bp) app.register_blueprint(bp)
if __name__ == "__main__": if __name__ == "__main__":
+69 -1
View File
@@ -1,5 +1,6 @@
from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify, Response, current_app, abort from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify, Response, current_app, abort
import json import json
from werkzeug.utils import secure_filename
from pathlib import Path from pathlib import Path
import random import random
import csv import csv
@@ -7,9 +8,12 @@ import hmac
import io import io
import os import os
import time import time
import re
import uuid
from functools import wraps from functools import wraps
from db import init_db, get_db, close_db, create_participant, now from db import init_db, get_db, close_db, create_participant, now
from datetime import datetime, timezone from datetime import datetime, timezone
import threading
bp = Blueprint("main", __name__) bp = Blueprint("main", __name__)
@@ -19,11 +23,40 @@ bp.teardown_app_request(close_db)
BASE_DIR = Path(__file__).parent BASE_DIR = Path(__file__).parent
BASE_MUSIC_DIR = BASE_DIR / "static" / "data" / "music" BASE_MUSIC_DIR = BASE_DIR / "static" / "data" / "music"
BASE_MUSIC_FILENAME_DIR = "data/music/" BASE_MUSIC_FILENAME_DIR = "data/music/"
SONGS_PATH = BASE_DIR / "data" / "songs.json"
_songs_lock = threading.Lock()
def load_songs_list(): def load_songs_list():
with open(BASE_DIR / "data" / "songs.json", encoding="utf-8") as f: with open(SONGS_PATH, encoding="utf-8") as f:
return json.load(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): def session_required(api=False, participant=True):
"""Prüft Datenschutz-Zustimmung und (optional) angelegten Teilnehmer. """Prüft Datenschutz-Zustimmung und (optional) angelegten Teilnehmer.
@@ -271,3 +304,38 @@ def debug_reset():
abort(404) # im normalen Betrieb existiert die Route praktisch nicht abort(404) # im normalen Betrieb existiert die Route praktisch nicht
session.clear() session.clear()
return redirect(url_for("main.login")) 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": stem},
"edits": [],
})
return jsonify({"saved": True, "filename": filename_new})
+54
View File
@@ -76,3 +76,57 @@ td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
.person .table-wrap { margin: 0; padding: 0 .5rem .5rem; } .person .table-wrap { margin: 0; padding: 0 .5rem .5rem; }
.muted, .empty { color: var(--muted); font-weight: 400; } .muted, .empty { color: var(--muted); font-weight: 400; }
.form label {
display: block;
margin-bottom: .25rem;
margin-top: 1rem;
font-size: .9rem;
color: var(--muted);
}
.form input,
.form button {
width: 100%;
font-size: 1rem; /* mind. 16px, sonst zoomt iOS beim Fokussieren hinein */
min-height: 2.75rem; /* gut mit dem Daumen treffbar */
}
.form button {
margin-top: 1rem;
}
.file-upload {
display: flex;
align-items: center;
gap: 0.75rem;
position: relative;
}
/* Das echte Input bleibt für Tastatur und Screenreader erreichbar, ist aber unsichtbar */
.file-upload input[type="file"] {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
overflow: hidden;
}
.file-button {
display: inline-block;
padding: 0.5rem 1rem;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--surface);
cursor: pointer;
font: inherit;
transition: background 0.15s, border-color 0.15s;
}
.file-name {
color: var(--text);
font-size: 0.9rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
+1
View File
@@ -7,6 +7,7 @@
<h2>Auswertung</h2> <h2>Auswertung</h2>
<div class="admin-actions"> <div class="admin-actions">
<a class="button" href="{{ url_for('main.admin_export') }}">CSV exportieren</a> <a class="button" href="{{ url_for('main.admin_export') }}">CSV exportieren</a>
<a class="button" href="{{ url_for('main.admin_add') }}">Unteraufgabe hinzufügen</a>
<form method="post" action="{{ url_for('main.admin_logout') }}"> <form method="post" action="{{ url_for('main.admin_logout') }}">
<button type="submit" class="secondary">Abmelden</button> <button type="submit" class="secondary">Abmelden</button>
</form> </form>
+44
View File
@@ -0,0 +1,44 @@
{% extends "base.html" %}
{% block content %}
<link rel="stylesheet" href="{{ url_for('static', filename='style/admin.css') }}">
<h2>Unteraufgabe hinzufügen</h2>
<form class="form" id="form">
<label for="titel">Titel</label>
<input id="title" name="title" type="text" autocomplete="off" required autofocus>
<label for="artist">Artist</label>
<input id="artist" name="artist" type="text" autocomplete="off">
<label for="file">Datei</label>
<div class="file-upload">
<input id="file" name="file" type="file" accept="audio/*,.mp3,.wav,.flac,.ogg,.m4a" required>
<label for="file" class="file-button">Audiodatei wählen</label>
<span class="file-name" id="file-name">Keine Datei ausgewählt</span>
</div>
<button type="submit">Erstellen</button>
</form>
<script>
const form = document.getElementById("form");
form.addEventListener("submit", async (event) => {
event.preventDefault();
const res = await fetch("/api/admin/add", {
method: "POST",
body: new FormData(form),
});
const result = await res.json();
console.log(result);
});
const fileInput = document.getElementById("file");
const fileName = document.getElementById("file-name");
fileInput.addEventListener("change", () => {
fileName.textContent = fileInput.files.length
? fileInput.files[0].name
: "Keine Datei ausgewählt";
});
</script>
{% endblock %}