diff --git a/VERSION b/VERSION index 880a8fb..1dce899 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1305 \ No newline at end of file +1306 \ No newline at end of file diff --git a/backend/database.py b/backend/database.py index 8fad182..6fef3be 100644 --- a/backend/database.py +++ b/backend/database.py @@ -530,6 +530,8 @@ def _migrate(conn_factory): ("forum_posts", "foto_urls", "TEXT"), ("forum_posts", "is_deleted", "INTEGER NOT NULL DEFAULT 0"), ("forum_posts", "likes", "INTEGER NOT NULL DEFAULT 0"), + # Idempotenz: Client-UUID gegen Doppelposts bei verlorener Antwort (Funkloch) + ("forum_posts", "client_uuid", "TEXT"), # Users: Moderator-Flag + Forum-Standort ("users", "is_moderator", "INTEGER NOT NULL DEFAULT 0"), ("users", "forum_lat", "REAL"), diff --git a/backend/routes/forum.py b/backend/routes/forum.py index f8943ac..f07c53c 100644 --- a/backend/routes/forum.py +++ b/backend/routes/forum.py @@ -38,6 +38,7 @@ class ThreadCreate(BaseModel): class PostCreate(BaseModel): text: str = Field(..., min_length=1, max_length=10000) client_time: Optional[str] = Field(None, max_length=64) + client_uuid: Optional[str] = Field(None, max_length=64) # Idempotenz-Schlüssel gegen Doppelposts class ThreadPatch(BaseModel): is_pinned: Optional[int] = None @@ -402,12 +403,30 @@ async def create_post(thread_id: int, data: PostCreate, user=Depends(get_current if thread['is_deleted']: raise HTTPException(404, "Thread nicht gefunden.") + # Idempotenz: Ein Retry mit derselben client_uuid (z.B. wenn die Antwort + # des 1. Versuchs im Funkloch verloren ging) liefert den BEREITS erstellten + # Post zurück — statt Cooldown-/Duplikat-Fehler oder Doppelpost. Der Client + # behält die UUID über Retries hinweg und setzt sie erst nach Erfolg zurück. + if data.client_uuid: + existing = conn.execute( + """SELECT p.*, u.name AS autor_name, u.founder_number AS autor_founder_number + FROM forum_posts p + LEFT JOIN users u ON u.id = p.user_id + WHERE p.user_id=? AND p.client_uuid=? AND p.thread_id=?""", + (user["id"], data.client_uuid, thread_id) + ).fetchone() + if existing: + ed = dict(existing) + ed['foto_urls'] = _parse_foto_urls(ed.get('foto_urls')) + ed['user_liked'] = _user_liked(conn, user["id"], 'post', ed['id']) + return ed + ct = safe_client_time(data.client_time) _check_post_limits(user["id"], conn, data.text.strip(), user.get("created_at"), is_thread=False, now_client=ct) cur = conn.execute( - "INSERT INTO forum_posts (thread_id, user_id, text, created_at) VALUES (?, ?, ?, ?)", - (thread_id, user['id'], data.text.strip(), ct) + "INSERT INTO forum_posts (thread_id, user_id, text, created_at, client_uuid) VALUES (?, ?, ?, ?, ?)", + (thread_id, user['id'], data.text.strip(), ct, data.client_uuid) ) conn.execute( "UPDATE forum_threads SET antworten = antworten + 1 WHERE id = ?", diff --git a/backend/static/index.html b/backend/static/index.html index e6747d5..cef6316 100644 --- a/backend/static/index.html +++ b/backend/static/index.html @@ -86,14 +86,14 @@ Ban Yaro - + - - - - - + + + + + @@ -624,12 +624,12 @@ - - - - - - + + + + + + @@ -639,7 +639,7 @@ - + diff --git a/backend/static/js/app.js b/backend/static/js/app.js index c6129a0..5e772d5 100644 --- a/backend/static/js/app.js +++ b/backend/static/js/app.js @@ -3,7 +3,7 @@ Router, State-Management, Navigation, Initialisierung. ============================================================ */ -const APP_VER = '1305'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen +const APP_VER = '1306'; // ← bei jedem Deploy mit Frontend-Änderungen erhöhen const APP_VERSION = '1.6.0'; // ← semantische Version, wird bei make release gesetzt window.APP_VER = APP_VER; // global verfügbar für andere Module (z.B. offline-indicator) window.APP_VERSION = APP_VERSION; diff --git a/backend/static/js/pages/forum.js b/backend/static/js/pages/forum.js index c9664b6..deee3dd 100644 --- a/backend/static/js/pages/forum.js +++ b/backend/static/js/pages/forum.js @@ -751,20 +751,33 @@ function _fmtDate(iso) { if (postsListEl) _bindPostActions(postsListEl, thread.id, uid, isMod); // Reply abschicken + // Idempotenz-Schlüssel: bleibt über Retries STABIL und wird erst nach + // erfolgreichem Senden zurückgesetzt. So liefert ein Retry (z.B. wenn die + // Antwort des 1. Versuchs im Funkloch verloren ging) denselben Post zurück + // statt eines Cooldown-Fehlers/Doppelposts. + let _replyUuid = null; document.getElementById('ft-reply')?.addEventListener('click', async () => { const btn = document.getElementById('ft-reply'); const text = document.getElementById('forum-reply-text')?.value?.trim(); if (!text) { UI.toast.warning('Bitte Text eingeben.'); return; } + if (!_replyUuid) { + _replyUuid = (window.crypto && crypto.randomUUID) + ? crypto.randomUUID() + : `${Date.now()}-${Math.random().toString(16).slice(2)}`; + } await UI.asyncButton(btn, async () => { - const post = await API.forum.addPost(thread.id, { text, client_time: API.clientNow() }); + const post = await API.forum.addPost(thread.id, { text, client_time: API.clientNow(), client_uuid: _replyUuid }); - // Foto hochladen falls vorhanden + // Foto hochladen falls vorhanden — bei idempotentem Retry hat der Post + // seine Fotos bereits, dann NICHT erneut hochladen (kein Doppel-Upload). const files = Array.from(document.getElementById('forum-reply-file')?.files || []); - for (const file of files.slice(0, 5)) { - try { - await API.forum.uploadPostFoto(post.id, file); - } catch (e) { /* Foto-Upload-Fehler ignorieren */ } + if (!post.foto_urls || post.foto_urls.length === 0) { + for (const file of files.slice(0, 5)) { + try { + await API.forum.uploadPostFoto(post.id, file); + } catch (e) { /* Foto-Upload-Fehler ignorieren */ } + } } thread.antworten = (thread.antworten || 0) + 1; @@ -782,6 +795,7 @@ function _fmtDate(iso) { document.getElementById('forum-reply-text').value = ''; const previews = document.getElementById('forum-reply-previews'); if (previews) previews.innerHTML = ''; + _replyUuid = null; // Erfolg → nächste Antwort bekommt eine frische UUID UI.toast.success('Antwort gesendet.'); }); }); diff --git a/backend/static/landing.html b/backend/static/landing.html index a75bb78..56fe66b 100644 --- a/backend/static/landing.html +++ b/backend/static/landing.html @@ -4,7 +4,7 @@ - + Ban Yaro — Die Hunde-App für Deutschland, Österreich & Schweiz diff --git a/backend/static/sw.js b/backend/static/sw.js index da22d33..af98aa8 100644 --- a/backend/static/sw.js +++ b/backend/static/sw.js @@ -4,7 +4,7 @@ ============================================================ */ // ← EINZIGE Stelle für die Version — STATIC_ASSETS und CACHE_VERSION leiten sich ab -const VER = '1305'; +const VER = '1306'; const CACHE_VERSION = `by-v${VER}`; const CACHE_STATIC = `${CACHE_VERSION}-static`; const CACHE_TILES = 'ban-yaro-tiles-v1'; // bleibt über SW-Updates erhalten diff --git a/tests/test_forum_idempotency.py b/tests/test_forum_idempotency.py new file mode 100644 index 0000000..7667746 --- /dev/null +++ b/tests/test_forum_idempotency.py @@ -0,0 +1,76 @@ +"""Forum-Antworten: Idempotenz gegen Doppelposts bei verlorener Antwort (Funkloch). + +Szenario aus der Praxis: Eine Antwort wird serverseitig erstellt, aber die HTTP- +Antwort erreicht das Handy nicht (schlechtes Netz). Der Nutzer tippt erneut auf +„Antworten". Mit stabiler client_uuid liefert der Retry denselben Post zurück — +statt 30-Sekunden-Cooldown-Fehler (429) oder Doppelpost. + +Cooldown/Duplikat-Checks sind NICHT gestubbt → client_time steuert die Zeitbasis. +""" + +from __future__ import annotations + +import secrets + + +def _mk_thread(client, headers, client_time): + r = client.post( + "/api/forum/threads", + headers=headers, + json={ + "kategorie": "allgemein", + "titel": "Idempotenz-Thread", + "text": f"Genug langer Thread-Text {secrets.token_hex(6)}.", + "client_time": client_time, + }, + ) + assert r.status_code == 201, f"thread create: {r.status_code} {r.text}" + return r.json() + + +def _reply(client, headers, thread_id, text, client_time, client_uuid=None): + body = {"text": text, "client_time": client_time} + if client_uuid is not None: + body["client_uuid"] = client_uuid + return client.post(f"/api/forum/threads/{thread_id}/posts", headers=headers, json=body) + + +def test_retry_same_uuid_returns_same_post_no_cooldown(client, user): + h = user["headers"] + t = _mk_thread(client, h, "2026-06-19T10:00:00") + + # 1. Antwort (60s nach Thread → kein Cooldown) + r1 = _reply(client, h, t["id"], "Oh ja das stimmt", "2026-06-19T10:01:00", client_uuid="uuid-A") + assert r1.status_code == 201, r1.text + pid = r1.json()["id"] + + # Retry mit SELBER UUID, nur 5s später (läge im 30s-Cooldown) → idempotent, + # liefert denselben Post zurück, KEIN 429. + r2 = _reply(client, h, t["id"], "Oh ja das stimmt", "2026-06-19T10:01:05", client_uuid="uuid-A") + assert r2.status_code == 201, r2.text + assert r2.json()["id"] == pid, "Retry muss den bereits erstellten Post zurückliefern" + + # Es darf nur EINE Antwort existieren (kein Doppelpost). + detail = client.get(f"/api/forum/threads/{t['id']}", headers=h).json() + assert detail["antworten"] == 1 + assert len([p for p in detail["posts"] if not p.get("is_deleted")]) == 1 + + +def test_cooldown_still_blocks_genuinely_new_reply(client, user): + h = user["headers"] + t = _mk_thread(client, h, "2026-06-19T10:00:00") + + r1 = _reply(client, h, t["id"], "Erste Antwort", "2026-06-19T10:01:00", client_uuid="uuid-1") + assert r1.status_code == 201, r1.text + + # Andere UUID + anderer Text, nur 10s später → echter Doppel-Post-Versuch → 429 + r2 = _reply(client, h, t["id"], "Zweite Antwort", "2026-06-19T10:01:10", client_uuid="uuid-2") + assert r2.status_code == 429, f"Cooldown muss greifen: {r2.status_code} {r2.text}" + + +def test_reply_without_uuid_still_works(client, user): + """Rückwärtskompatibel: Antwort ohne client_uuid bleibt 201.""" + h = user["headers"] + t = _mk_thread(client, h, "2026-06-19T10:00:00") + r = _reply(client, h, t["id"], "Antwort ohne UUID", "2026-06-19T10:01:00") + assert r.status_code == 201, r.text