6 Commits

Author SHA1 Message Date
MechaCat02
5b2947cdbe docs: add admin & host dashboard test steps (Steps 10–15) 2026-04-03 19:31:04 +02:00
MechaCat02
0351e967c0 feat: unique display names + inline recover on join (v0.13.1)
Backend: migration 007 adds a case-insensitive unique index on user names
per event. join endpoint returns 409 conflict when the name is taken.
find_by_event_and_name uses LOWER() for case-insensitive recovery.

Frontend: join page handles 409 with a name-taken view — amber warning,
name-choice tips, inline PIN recovery form, and "Anderen Namen wählen"
button. Test guide updated with Steps 8 and 9.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 18:37:51 +02:00
MechaCat02
de0e395a9e feat: auto-retry uploads when rate limited (v0.13.0)
Backend: rate limiter gains check_with_retry() returning seconds until
the next slot opens. Upload 429 responses include retry_after_secs in
JSON and a Retry-After header.

Frontend: upload queue catches 429 as RateLimitError, resets affected
item to pending, schedules processQueue() for the server-reported delay,
and shows a live countdown banner in the queue UI.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 18:37:51 +02:00
MechaCat02
3dc69e6c6d fix: upload body limit, role case, and connection drain (v0.12.1)
- Disable Axum's 2 MB default body limit on the upload route so large
  photos/videos are accepted without HTTP 400
- Serialize UserRole as lowercase in JWT so the frontend role checks
  ('guest'/'host'/'admin') match correctly
- Drain multipart body before returning early upload errors (rate-limit,
  ban, event-lock) to keep the HTTP keep-alive connection clean and
  prevent cascading Netzwerkfehler / empty-500 responses
- Add TraceLayer for request logging and Vite dev proxy config

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 18:14:12 +02:00
MechaCat02
87b5aff478 feat: implement onboarding guide and HTML export guide
Add 4-step dismissible onboarding overlay shown on first feed visit
(welcome, upload, hashtags, PIN importance). Dismissed state persisted
in localStorage under eventsnap_guide_seen. Step indicator dots and
skip/continue buttons included.

Update HTML export guide modal to persist the eventsnap_html_guide_seen
flag: first download shows the instructions modal; subsequent clicks go
straight to download without interruption.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 21:13:14 +02:00
MechaCat02
75d186fad3 feat: implement My Account page
Add /account route showing display name (from localStorage), role badge,
session expiry decoded from JWT, and recovery PIN display with copy button.
Join and recover flows now persist display_name to localStorage via setAuth().
Feed header logout button replaced with person-icon link to /account;
logout is available from the account page.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-02 21:11:11 +02:00
21 changed files with 681 additions and 65 deletions

123
TEST_GUIDE.md Normal file
View File

@@ -0,0 +1,123 @@
## Frontend Testing — Step by Step
Please test each step in order and report any errors (console errors, wrong text, broken UI, API errors).
### Step 1 — Join flow + PIN modal
1. Open **http://localhost:5173/** in your browser (or navigate there if already open)
2. You should land on the **join page** (`/join`) with a name input
3. Enter your name (e.g. `Max`) and click **Beitreten**
4. ✅ Expected: A modal appears showing your 4-digit PIN in large monospace font with a "Kopieren" button
5. Click **Weiter zur Galerie**
### Step 2 — Onboarding guide
6. You should land on the **feed page** (`/feed`)
7. ✅ Expected: A dark overlay appears at the bottom (or center on desktop) — the onboarding guide — showing step 1 of 4 with a step indicator and the Willkommen screen
8. Click **Weiter** through all 4 steps, then **Los geht's!**
9. ✅ Expected: Overlay disappears
### Step 3 — Feed & navigation
10. ✅ Expected: Feed shows "Noch keine Fotos." empty state with an upload button
11. ✅ Expected: Top-right has an **upload button** (blue) and a **person icon** link
### Step 4 — My Account page
12. Click the **person icon** in the top-right
13. ✅ Expected: `/account` page shows your name (`Max`), a blue "Gast" badge, session expiry date, and your PIN displayed large in an amber box
14. Click **Kopieren** — check clipboard contains your PIN
15. ✅ Expected: Button briefly shows "Kopiert!"
16. Click **Zur Galerie** to go back to the feed
### Step 5 — Upload
17. Click **Hochladen** — this takes you to `/upload`
18. Try uploading a photo from your device library
19. ✅ Expected: Photo appears in queue with a progress bar, then completes
20. Go back to `/feed` — ✅ Expected: your photo appears in the feed grid
### Step 6 — Onboarding guide not shown again
21. Reload the page at `/feed`
22. ✅ Expected: The onboarding overlay does **not** appear (already dismissed)
### Step 7 — Recover (open a private/incognito window)
23. Open a new **private/incognito** window at **http://localhost:5173/recover**
24. Enter the same name (`Max`) and the PIN you copied
25. ✅ Expected: You're redirected to the feed with the same account
### Step 8 — Upload rate-limit auto-retry
26. Upload more than 20 photos in one hour to trigger the rate limit
27. ✅ Expected: When the limit is hit, remaining items stay **Wartend** (not error)
28. ✅ Expected: An amber banner appears in the queue: "Upload-Limit erreicht. Wird in Xs automatisch fortgesetzt."
29. ✅ Expected: The countdown ticks down and uploads resume automatically when it reaches 0
### Step 9 — Name uniqueness (case-insensitive)
30. In a private/incognito window go to **http://localhost:5173/join**
31. Enter `max` or `MAX` — the same name already taken in Step 1 (different case)
32. ✅ Expected: Instead of creating a new account, an amber warning appears: „Max ist bereits vergeben." with name tips
33. ✅ Expected: A PIN input and **Anmelden** button appear, plus an **Anderen Namen wählen** button
34. Enter your PIN from Step 1 and click **Anmelden**
35. ✅ Expected: You're signed in to the existing `Max` account and redirected to the feed
36. Alternatively, click **Anderen Namen wählen** — ✅ Expected: the name input reappears with `max` pre-filled so you can edit it
---
## Admin & Host Features
For these steps you need an admin session. Log in via the admin API (or use the curl command below):
```bash
curl -s -X POST http://localhost:3000/api/v1/admin/login \
-H 'Content-Type: application/json' \
-d '{"password":"admin123"}' | python3 -m json.tool
```
Copy the `jwt` value — you'll need it for the Authorization header in curl commands.
To use the admin dashboard in the browser, paste the token into DevTools console:
```js
localStorage.setItem('token', '<jwt>');
localStorage.setItem('role', 'admin');
```
Then navigate to **http://localhost:5173/admin**.
### Step 10 — Admin Dashboard: Stats & Config
1. Go to **http://localhost:5173/admin**
2. ✅ Expected: Stats card shows user count, upload count, comment count, and a disk-usage progress bar
3. In the **Konfiguration** section, change **Upload-Limit pro Stunde** to a different value (e.g. `5`) and click **Speichern**
4. ✅ Expected: Toast "Konfiguration gespeichert." appears briefly
5. Reload — ✅ Expected: the changed value persists
### Step 11 — Admin Dashboard: Export Jobs
6. The **Export-Jobs** section shows all past jobs (likely empty if gallery hasn't been released yet)
7. Click **Aktualisieren** — ✅ Expected: list refreshes without a full page reload
### Step 12 — Host Dashboard: Event Controls
8. Navigate to **http://localhost:5173/host** (or click "Host-Dashboard" from the admin page)
9. ✅ Expected: Event name shown in the header; two status dots (Uploads open/locked, Export released/locked)
10. Click **Uploads sperren**
11. ✅ Expected: Toast "Uploads wurden gesperrt."; button changes to "Uploads wieder öffnen"; status dot turns red
12. Try uploading a photo as a guest — ✅ Expected: "Uploads sind gesperrt." error
13. Click **Uploads wieder öffnen** — ✅ Expected: dot turns green; uploads work again
### Step 13 — Host Dashboard: User Management
14. The **Gäste** list shows all registered users with upload counts and sizes
15. Find a guest and click **Host** next to their name
16. ✅ Expected: Toast "X ist jetzt Host."; a blue "Host" badge appears next to their name
17. As admin, a **Degradieren** button is now visible — click it
18. ✅ Expected: Toast "X ist jetzt Gast."; badge disappears
### Step 14 — Host Dashboard: Ban & Unban
19. Click **Sperren** next to a guest
20. ✅ Expected: A confirmation modal opens asking what to do with their uploads, with a checkbox "Uploads aus der Galerie ausblenden"
21. Leave the checkbox unchecked and click **Sperren**
22. ✅ Expected: Toast "X wurde gesperrt."; a red "Gesperrt" badge appears; buttons change to **Entsperren**
23. Try uploading as that banned user — ✅ Expected: "Du bist gesperrt." error
24. Click **Entsperren** — ✅ Expected: ban lifted; badge gone
### Step 15 — Gallery Release & Export
25. Make sure you have at least a few photos uploaded, then on the Host Dashboard click **Galerie freigeben**
26. ✅ Expected: Toast "Galerie wurde freigegeben. Export wird vorbereitet…"; button becomes disabled "Galerie bereits freigegeben"
27. Navigate to **http://localhost:5173/export** as any logged-in user
28. ✅ Expected: Two cards — **ZIP-Archiv** and **HTML-Viewer** — both initially showing "Wird vorbereitet…" or a progress bar
29. Wait for both to show "Bereit zum Download" (reload or wait for SSE to update the UI)
30. Click **Download** on the ZIP card — ✅ Expected: `Gallery.zip` downloads
31. Click **Download** on the HTML card — ✅ Expected: A guide modal appears explaining how to open the file; click **Herunterladen** to get `Memories.zip`
32. In the Admin Dashboard → **Export-Jobs**, click **Aktualisieren** — ✅ Expected: both jobs show "Fertig" with green badges

View File

@@ -0,0 +1,4 @@
DROP INDEX IF EXISTS idx_user_event_name_ci;
CREATE INDEX idx_user_event_name
ON "user"(event_id, display_name);

View File

@@ -0,0 +1,15 @@
-- Deduplicate users with the same name (case-insensitive) per event,
-- keeping the oldest account so no real data is lost.
DELETE FROM "user"
WHERE id NOT IN (
SELECT DISTINCT ON (event_id, LOWER(display_name)) id
FROM "user"
ORDER BY event_id, LOWER(display_name), created_at ASC
);
-- Drop the old non-unique index (replaced below)
DROP INDEX IF EXISTS idx_user_event_name;
-- Unique index enforces one account per name per event (case-insensitive)
CREATE UNIQUE INDEX idx_user_event_name_ci
ON "user" (event_id, LOWER(display_name));

View File

@@ -39,6 +39,7 @@ pub async fn join(
if !state.rate_limiter.check(format!("join:{ip}"), 5, Duration::from_secs(60)) {
return Err(AppError::TooManyRequests(
"Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(),
None,
));
}
@@ -56,6 +57,14 @@ pub async fn join(
)
.await?;
// Reject if a user with this name (case-insensitive) already exists
if User::name_taken(&state.pool, event.id, display_name).await? {
return Err(AppError::Conflict(format!(
"Der Name \"{}\" ist bereits vergeben.",
display_name
)));
}
// Generate a 4-digit PIN
let pin: String = format!("{:04}", rand::rng().random_range(0..10000u32));
let pin_hash =
@@ -124,6 +133,7 @@ pub async fn recover(
if Utc::now() < locked_until {
return Err(AppError::TooManyRequests(
"Zu viele Versuche. Bitte warte 15 Minuten.".into(),
None,
));
}
}

View File

@@ -1,6 +1,5 @@
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde_json::json;
#[derive(Debug)]
pub enum AppError {
@@ -8,7 +7,9 @@ pub enum AppError {
Unauthorized(String),
Forbidden(String),
NotFound(String),
TooManyRequests(String),
Conflict(String),
/// Second field: optional retry-after seconds to include in the response.
TooManyRequests(String, Option<u64>),
Internal(anyhow::Error),
}
@@ -19,7 +20,8 @@ impl AppError {
Self::Unauthorized(_) => (StatusCode::UNAUTHORIZED, "unauthorized"),
Self::Forbidden(_) => (StatusCode::FORBIDDEN, "forbidden"),
Self::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
Self::TooManyRequests(_) => (StatusCode::TOO_MANY_REQUESTS, "too_many_requests"),
Self::Conflict(_) => (StatusCode::CONFLICT, "conflict"),
Self::TooManyRequests(..) => (StatusCode::TOO_MANY_REQUESTS, "too_many_requests"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
}
}
@@ -30,7 +32,8 @@ impl AppError {
| Self::Unauthorized(msg)
| Self::Forbidden(msg)
| Self::NotFound(msg)
| Self::TooManyRequests(msg) => msg.clone(),
| Self::Conflict(msg) => msg.clone(),
Self::TooManyRequests(msg, _) => msg.clone(),
Self::Internal(err) => {
tracing::error!("internal error: {err:#}");
"Ein interner Fehler ist aufgetreten.".to_string()
@@ -42,13 +45,29 @@ impl AppError {
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, code) = self.status_and_code();
let retry_after_secs = if let Self::TooManyRequests(_, Some(secs)) = &self {
Some(*secs)
} else {
None
};
let message = self.message();
let body = json!({
let mut body = serde_json::json!({
"error": code,
"message": message,
"status": status.as_u16(),
});
(status, axum::Json(body)).into_response()
if let Some(secs) = retry_after_secs {
body["retry_after_secs"] = secs.into();
}
let mut resp = (status, axum::Json(body)).into_response();
if let Some(secs) = retry_after_secs {
if let Ok(val) = axum::http::HeaderValue::from_str(&secs.to_string()) {
resp.headers_mut().insert(axum::http::header::RETRY_AFTER, val);
}
}
resp
}
}

View File

@@ -180,9 +180,7 @@ pub async fn download_zip(
let ip = client_ip(&headers, "unknown");
let limit = get_config_usize(&state.pool, "export_rate_per_day", 3).await;
if !state.rate_limiter.check(format!("export:{ip}"), limit, Duration::from_secs(86400)) {
return Err(AppError::TooManyRequests(
"Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(),
));
return Err(AppError::TooManyRequests("Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(), None));
}
let event = crate::models::event::Event::find_by_slug(&state.pool, &state.config.event_slug)
@@ -211,9 +209,7 @@ pub async fn download_html(
let ip = client_ip(&headers, "unknown");
let limit = get_config_usize(&state.pool, "export_rate_per_day", 3).await;
if !state.rate_limiter.check(format!("export:{ip}"), limit, Duration::from_secs(86400)) {
return Err(AppError::TooManyRequests(
"Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(),
));
return Err(AppError::TooManyRequests("Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(), None));
}
let event = crate::models::event::Event::find_by_slug(&state.pool, &state.config.event_slug)

View File

@@ -63,9 +63,7 @@ pub async fn feed(
let ip = client_ip(&headers, "unknown");
let rate_limit = get_config_usize(&state.pool, "feed_rate_per_min", 60).await;
if !state.rate_limiter.check(format!("feed:{ip}"), rate_limit, Duration::from_secs(60)) {
return Err(AppError::TooManyRequests(
"Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(),
));
return Err(AppError::TooManyRequests("Zu viele Anfragen. Bitte warte kurz und versuche es erneut.".into(), None));
}
let limit = q.limit.unwrap_or(20).min(100);

View File

@@ -20,12 +20,14 @@ pub async fn upload(
) -> Result<(StatusCode, Json<UploadDto>), AppError> {
// Rate limit: N uploads per hour per user
let upload_rate = get_config_i64(&state.pool, "upload_rate_per_hour", 10).await as usize;
if !state
if let Err(retry_after_secs) = state
.rate_limiter
.check(format!("upload:{}", auth.user_id), upload_rate, Duration::from_secs(3600))
.check_with_retry(format!("upload:{}", auth.user_id), upload_rate, Duration::from_secs(3600))
{
drain_multipart(multipart).await;
return Err(AppError::TooManyRequests(
"Du hast dein Upload-Limit für diese Stunde erreicht.".into(),
Some(retry_after_secs),
));
}
@@ -34,6 +36,7 @@ pub async fn upload(
.await?
.ok_or_else(|| AppError::NotFound("Benutzer nicht gefunden.".into()))?;
if user.is_banned {
drain_multipart(multipart).await;
return Err(AppError::Forbidden("Du bist gesperrt.".into()));
}
@@ -42,6 +45,7 @@ pub async fn upload(
.await?
.ok_or_else(|| AppError::NotFound("Event nicht gefunden.".into()))?;
if event.uploads_locked_at.is_some() {
drain_multipart(multipart).await;
return Err(AppError::Forbidden("Uploads sind gesperrt.".into()));
}
@@ -239,6 +243,15 @@ pub async fn delete_upload(
Ok(StatusCode::NO_CONTENT)
}
/// Drain a multipart body so the HTTP connection stays clean when returning an early error.
/// Without draining, the client may still be sending the body after we've sent our response,
/// which can corrupt the keep-alive connection for subsequent requests.
async fn drain_multipart(mut mp: Multipart) {
while let Ok(Some(mut field)) = mp.next_field().await {
while field.chunk().await.ok().flatten().is_some() {}
}
}
async fn get_config_i64(pool: &sqlx::PgPool, key: &str, default: i64) -> i64 {
let row: Option<(String,)> =
sqlx::query_as("SELECT value FROM config WHERE key = $1")

View File

@@ -1,7 +1,9 @@
use anyhow::Result;
use axum::extract::DefaultBodyLimit;
use axum::routing::{delete, get, patch, post};
use axum::Router;
use tower_http::services::ServeDir;
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
mod auth;
@@ -40,8 +42,9 @@ async fn main() -> Result<()> {
.route("/api/v1/recover", post(auth::handlers::recover))
.route("/api/v1/admin/login", post(auth::handlers::admin_login))
.route("/api/v1/session", delete(auth::handlers::logout))
// Upload
.route("/api/v1/upload", post(handlers::upload::upload))
// Upload — body limit disabled; size validation is done inside the handler
.route("/api/v1/upload", post(handlers::upload::upload)
.route_layer(DefaultBodyLimit::disable()))
.route(
"/api/v1/upload/{id}",
patch(handlers::upload::edit_upload).delete(handlers::upload::delete_upload),
@@ -89,6 +92,7 @@ async fn main() -> Result<()> {
.route("/health", get(|| async { "ok" }))
.merge(api)
.nest_service("/media", media_service)
.layer(TraceLayer::new_for_http())
.with_state(state);
let listener = tokio::net::TcpListener::bind(("0.0.0.0", config.app_port)).await?;

View File

@@ -4,6 +4,7 @@ use sqlx::PgPool;
use uuid::Uuid;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]
#[serde(rename_all = "lowercase")]
#[sqlx(type_name = "user_role", rename_all = "lowercase")]
pub enum UserRole {
Guest,
@@ -58,7 +59,7 @@ impl User {
display_name: &str,
) -> Result<Vec<Self>, sqlx::Error> {
sqlx::query_as::<_, Self>(
"SELECT * FROM \"user\" WHERE event_id = $1 AND display_name = $2",
"SELECT * FROM \"user\" WHERE event_id = $1 AND LOWER(display_name) = LOWER($2)",
)
.bind(event_id)
.bind(display_name)
@@ -66,6 +67,21 @@ impl User {
.await
}
pub async fn name_taken(
pool: &PgPool,
event_id: Uuid,
display_name: &str,
) -> Result<bool, sqlx::Error> {
let row: (bool,) = sqlx::query_as(
"SELECT EXISTS(SELECT 1 FROM \"user\" WHERE event_id = $1 AND LOWER(display_name) = LOWER($2))",
)
.bind(event_id)
.bind(display_name)
.fetch_one(pool)
.await?;
Ok(row.0)
}
pub async fn increment_failed_pin(pool: &PgPool, id: Uuid) -> Result<i16, sqlx::Error> {
let row: (i16,) = sqlx::query_as(
"UPDATE \"user\"

View File

@@ -19,17 +19,26 @@ impl RateLimiter {
/// Returns `true` if the request is allowed, `false` if rate-limited.
pub fn check(&self, key: impl Into<String>, max: usize, window: Duration) -> bool {
self.check_with_retry(key, max, window).is_ok()
}
/// Returns `Ok(())` if allowed, `Err(retry_after_secs)` if rate-limited.
/// `retry_after_secs` is how long until the oldest slot in the window expires.
pub fn check_with_retry(&self, key: impl Into<String>, max: usize, window: Duration) -> Result<(), u64> {
let now = Instant::now();
let key = key.into();
let mut map = self.windows.lock().unwrap();
let timestamps = map.entry(key).or_default();
// Drop entries outside the window
timestamps.retain(|&t| now.duration_since(t) < window);
if timestamps.len() < max {
timestamps.push(now);
true
Ok(())
} else {
false
// The oldest timestamp expires at oldest + window; compute remaining seconds
let oldest = timestamps[0];
let elapsed = now.duration_since(oldest);
let remaining = window.saturating_sub(elapsed);
Err(remaining.as_secs().max(1))
}
}
}

View File

@@ -4,6 +4,7 @@ import { browser } from '$app/environment';
const TOKEN_KEY = 'eventsnap_jwt';
const PIN_KEY = 'eventsnap_pin';
const USER_ID_KEY = 'eventsnap_user_id';
const DISPLAY_NAME_KEY = 'eventsnap_display_name';
export const isAuthenticated = writable(false);
@@ -22,11 +23,28 @@ export function getUserId(): string | null {
return localStorage.getItem(USER_ID_KEY);
}
export function setAuth(jwt: string, pin: string | null, userId: string): void {
export function getDisplayName(): string | null {
if (!browser) return null;
return localStorage.getItem(DISPLAY_NAME_KEY);
}
export function getExpiry(): Date | null {
const token = getToken();
if (!token) return null;
try {
const payload = JSON.parse(atob(token.split('.')[1]));
return payload.exp ? new Date(payload.exp * 1000) : null;
} catch {
return null;
}
}
export function setAuth(jwt: string, pin: string | null, userId: string, displayName?: string): void {
if (!browser) return;
localStorage.setItem(TOKEN_KEY, jwt);
if (pin) localStorage.setItem(PIN_KEY, pin);
localStorage.setItem(USER_ID_KEY, userId);
if (displayName) localStorage.setItem(DISPLAY_NAME_KEY, displayName);
isAuthenticated.set(true);
}

View File

@@ -0,0 +1,85 @@
<script lang="ts">
import { browser } from '$app/environment';
const GUIDE_SEEN_KEY = 'eventsnap_guide_seen';
let visible = $state(false);
let step = $state(0);
const steps = [
{
icon: '📸',
title: 'Willkommen bei EventSnap!',
body: 'Hier kannst du Fotos und Videos mit allen Gästen teilen — in Echtzeit, ganz ohne App-Store.'
},
{
icon: '⬆️',
title: 'Fotos & Videos hochladen',
body: 'Tippe oben auf „Hochladen", um Fotos aus deiner Galerie oder direkt mit der Kamera aufzunehmen. Mehrere Dateien auf einmal sind kein Problem!'
},
{
icon: '#️⃣',
title: 'Hashtags nutzen',
body: 'Füge in deiner Bildunterschrift #hashtags ein, um Fotos zu gruppieren — z.B. #tanz, #buffet oder #reden. Du kannst danach filtern.'
},
{
icon: '🔑',
title: 'Deinen PIN merken!',
body: 'Du hast beim Registrieren einen 4-stelligen PIN erhalten. Speichere ihn — du brauchst ihn, um dein Konto auf einem anderen Gerät wiederherzustellen. Er ist immer unter „Mein Konto" zu finden.'
}
];
if (browser && !localStorage.getItem(GUIDE_SEEN_KEY)) {
visible = true;
}
function next() {
if (step < steps.length - 1) {
step++;
} else {
dismiss();
}
}
function dismiss() {
if (browser) localStorage.setItem(GUIDE_SEEN_KEY, '1');
visible = false;
}
</script>
{#if visible}
<!-- Backdrop -->
<div class="fixed inset-0 z-50 flex items-end justify-center bg-black/60 sm:items-center">
<div class="w-full max-w-sm rounded-t-3xl bg-white p-6 shadow-2xl sm:rounded-2xl">
<!-- Step indicator -->
<div class="mb-5 flex justify-center gap-1.5">
{#each steps as _, i}
<div class="h-1.5 rounded-full transition-all {i === step ? 'w-6 bg-blue-600' : 'w-1.5 bg-gray-200'}"></div>
{/each}
</div>
<!-- Content -->
<div class="mb-6 text-center">
<div class="mb-3 text-5xl">{steps[step].icon}</div>
<h2 class="mb-2 text-xl font-bold text-gray-900">{steps[step].title}</h2>
<p class="text-sm leading-relaxed text-gray-600">{steps[step].body}</p>
</div>
<!-- Buttons -->
<div class="flex gap-2">
<button
onclick={dismiss}
class="flex-1 rounded-xl border border-gray-200 py-3 text-sm text-gray-500 hover:bg-gray-50"
>
Überspringen
</button>
<button
onclick={next}
class="flex-1 rounded-xl bg-blue-600 py-3 text-sm font-semibold text-white hover:bg-blue-700"
>
{step < steps.length - 1 ? 'Weiter' : 'Los geht\'s!'}
</button>
</div>
</div>
</div>
{/if}

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import { queueItems, isProcessing, retryItem, removeItem, clearCompleted } from '$lib/upload-queue';
import { queueItems, isProcessing, retryItem, removeItem, clearCompleted, rateLimitRetryAt } from '$lib/upload-queue';
import type { QueueItem } from '$lib/upload-queue';
function formatSize(bytes: number): string {
@@ -28,6 +28,25 @@
let items = $derived($queueItems);
let hasCompleted = $derived(items.some((i) => i.status === 'done'));
// Countdown for rate-limit banner
let countdown = $state(0);
$effect(() => {
const retryAt = $rateLimitRetryAt;
if (!retryAt) {
countdown = 0;
return;
}
countdown = Math.ceil((retryAt - Date.now()) / 1000);
const interval = setInterval(() => {
countdown = Math.ceil((retryAt - Date.now()) / 1000);
if (countdown <= 0) clearInterval(interval);
}, 1000);
return () => clearInterval(interval);
});
</script>
{#if items.length > 0}
@@ -49,6 +68,12 @@
{/if}
</div>
{#if $rateLimitRetryAt && countdown > 0}
<div class="border-b border-amber-100 bg-amber-50 px-4 py-2 text-sm text-amber-800">
Upload-Limit erreicht. Wird in {countdown} Sek. automatisch fortgesetzt.
</div>
{/if}
<ul class="divide-y divide-gray-100">
{#each items as item (item.id)}
<li class="px-4 py-3">

View File

@@ -18,6 +18,9 @@ export interface QueueItem {
export const queueItems = writable<QueueItem[]>([]);
export const isProcessing = writable(false);
/** Set to the timestamp (ms) at which the rate-limit lifts, or null when clear. */
export const rateLimitRetryAt = writable<number | null>(null);
const DB_NAME = 'eventsnap-uploads';
const STORE_NAME = 'queue';
@@ -35,6 +38,14 @@ async function getDb(): Promise<IDBPDatabase> {
return db;
}
class RateLimitError extends Error {
retryAfterSecs: number;
constructor(secs: number) {
super('rate_limited');
this.retryAfterSecs = secs;
}
}
export async function loadQueue(): Promise<void> {
const database = await getDb();
const all = await database.getAll(STORE_NAME);
@@ -136,7 +147,21 @@ async function processQueue(): Promise<void> {
const next = items.find((item) => item.status === 'pending');
if (!next) break;
await uploadItem(next.id);
try {
await uploadItem(next.id);
} catch (e) {
if (e instanceof RateLimitError) {
// Keep all pending items as-is; schedule queue resume when limit lifts
const retryAt = Date.now() + e.retryAfterSecs * 1000;
rateLimitRetryAt.set(retryAt);
setTimeout(() => {
rateLimitRetryAt.set(null);
processQueue();
}, e.retryAfterSecs * 1000);
break;
}
// Other errors are already handled inside uploadItem (marked as 'error')
}
}
} finally {
processing = false;
@@ -148,7 +173,6 @@ async function uploadItem(id: string): Promise<void> {
const database = await getDb();
const entry = await database.get(STORE_NAME, id);
if (!entry || !entry.blob) {
// No blob — mark as error
updateItemStatus(id, 'error', 'Datei nicht gefunden.');
return;
}
@@ -184,6 +208,14 @@ async function uploadItem(id: string): Promise<void> {
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve();
} else if (xhr.status === 429) {
try {
const body = JSON.parse(xhr.responseText);
const secs = typeof body.retry_after_secs === 'number' ? body.retry_after_secs : 60;
reject(new RateLimitError(secs));
} catch {
reject(new RateLimitError(60));
}
} else {
try {
const body = JSON.parse(xhr.responseText);
@@ -205,6 +237,13 @@ async function uploadItem(id: string): Promise<void> {
await database.put(STORE_NAME, entry);
updateItemStatus(id, 'done');
} catch (e) {
if (e instanceof RateLimitError) {
// Reset to pending so it will be retried when the queue resumes
entry.status = 'pending';
await database.put(STORE_NAME, entry);
updateItemStatus(id, 'pending');
throw e; // Propagate to processQueue for scheduling
}
const msg = e instanceof Error ? e.message : 'Upload fehlgeschlagen.';
entry.status = 'error';
entry.error = msg;
@@ -224,7 +263,7 @@ function updateItemStatus(
? {
...item,
status,
progress: status === 'done' ? 100 : status === 'error' ? item.progress : item.progress,
progress: status === 'done' ? 100 : status === 'pending' ? 0 : item.progress,
error
}
: item

View File

@@ -0,0 +1,137 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { getToken, getPin, getDisplayName, getExpiry, getRole, clearAuth } from '$lib/auth';
import { api } from '$lib/api';
import { browser } from '$app/environment';
import { onMount } from 'svelte';
let pin = $state<string | null>(null);
let displayName = $state<string | null>(null);
let role = $state<'guest' | 'host' | 'admin' | null>(null);
let expiry = $state<Date | null>(null);
let copied = $state(false);
let pinCopied = $state(false);
onMount(() => {
if (!getToken()) {
goto('/join');
return;
}
pin = getPin();
displayName = getDisplayName();
role = getRole();
expiry = getExpiry();
});
function copyPin() {
if (!pin) return;
navigator.clipboard.writeText(pin);
pinCopied = true;
setTimeout(() => (pinCopied = false), 2000);
}
async function handleLogout() {
try { await api.delete('/session'); } catch { /* ignore */ }
clearAuth();
goto('/join');
}
function formatDate(d: Date): string {
return d.toLocaleDateString('de-DE', { day: '2-digit', month: 'long', year: 'numeric' });
}
function roleLabel(r: string | null): string {
switch (r) {
case 'admin': return 'Admin';
case 'host': return 'Gastgeber';
default: return 'Gast';
}
}
function roleColor(r: string | null): string {
switch (r) {
case 'admin': return 'bg-red-100 text-red-700';
case 'host': return 'bg-purple-100 text-purple-700';
default: return 'bg-blue-100 text-blue-700';
}
}
</script>
<div class="min-h-screen bg-gray-50">
<!-- Header -->
<div class="border-b border-gray-200 bg-white">
<div class="mx-auto flex max-w-lg items-center justify-between px-4 py-4">
<h1 class="text-xl font-bold text-gray-900">Mein Konto</h1>
<a href="/feed" class="text-sm text-blue-600 hover:underline">Zur Galerie</a>
</div>
</div>
<div class="mx-auto max-w-lg space-y-4 p-4">
<!-- Profile card -->
<div class="rounded-xl border border-gray-200 bg-white p-5">
<div class="flex items-center gap-3">
<div class="flex h-12 w-12 items-center justify-center rounded-full bg-blue-100 text-xl font-bold text-blue-600">
{#if displayName}
{displayName[0].toUpperCase()}
{:else}
?
{/if}
</div>
<div>
<p class="font-semibold text-gray-900">{displayName ?? 'Unbekannt'}</p>
<span class="inline-block rounded-full px-2 py-0.5 text-xs font-medium {roleColor(role)}">
{roleLabel(role)}
</span>
</div>
</div>
{#if expiry}
<p class="mt-3 text-xs text-gray-400">Sitzung gültig bis {formatDate(expiry)}</p>
{/if}
</div>
<!-- PIN card -->
<div class="rounded-xl border border-amber-200 bg-amber-50 p-5">
<h2 class="mb-1 font-semibold text-amber-900">Wiederherstellungs-PIN</h2>
<p class="mb-3 text-sm text-amber-700">
Du brauchst diesen PIN, um dein Konto auf einem anderen Gerät wiederherzustellen. Schreib ihn auf!
</p>
{#if pin}
<div class="flex items-center justify-between rounded-lg bg-white px-4 py-3 shadow-sm">
<span class="font-mono text-4xl font-bold tracking-widest text-gray-900">{pin}</span>
<button
onclick={copyPin}
class="rounded-md bg-amber-100 px-3 py-1.5 text-sm font-medium text-amber-800 transition hover:bg-amber-200"
>
{pinCopied ? 'Kopiert!' : 'Kopieren'}
</button>
</div>
{:else}
<div class="rounded-lg bg-white px-4 py-3 text-sm text-gray-400 shadow-sm">
PIN nicht gespeichert. Nutze die Wiederherstellungs-Seite, um dich mit deinem PIN anzumelden.
</div>
{/if}
</div>
<!-- Recovery hint -->
<div class="rounded-xl border border-gray-200 bg-white p-5">
<h2 class="mb-1 font-semibold text-gray-900">Gerät wechseln?</h2>
<p class="text-sm text-gray-600">
Auf einem anderen Gerät kannst du dein Konto mit deinem Namen und PIN wiederherstellen.
</p>
<a
href="/recover"
class="mt-3 inline-block text-sm font-medium text-blue-600 hover:underline"
>
Zur Wiederherstellungs-Seite →
</a>
</div>
<!-- Logout -->
<button
onclick={handleLogout}
class="w-full rounded-xl border border-red-200 bg-white py-3 text-sm font-medium text-red-600 transition hover:bg-red-50"
>
Abmelden
</button>
</div>
</div>

View File

@@ -16,6 +16,8 @@
html: JobStatus;
}
const HTML_GUIDE_KEY = 'eventsnap_html_guide_seen';
let status = $state<ExportStatus | null>(null);
let showHtmlGuide = $state(false);
let loading = $state(true);
@@ -75,10 +77,15 @@
}
function downloadHtml() {
showHtmlGuide = true;
if (localStorage.getItem(HTML_GUIDE_KEY)) {
window.location.href = '/api/v1/export/html';
} else {
showHtmlGuide = true;
}
}
function confirmHtmlDownload() {
localStorage.setItem(HTML_GUIDE_KEY, '1');
showHtmlGuide = false;
window.location.href = '/api/v1/export/html';
}

View File

@@ -1,12 +1,13 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { getToken, clearAuth } from '$lib/auth';
import { getToken } from '$lib/auth';
import { api } from '$lib/api';
import { connectSse, disconnectSse, onSseEvent } from '$lib/sse';
import { onMount, onDestroy } from 'svelte';
import FeedGrid from '$lib/components/FeedGrid.svelte';
import HashtagChips from '$lib/components/HashtagChips.svelte';
import LightboxModal from '$lib/components/LightboxModal.svelte';
import OnboardingGuide from '$lib/components/OnboardingGuide.svelte';
import type { FeedUpload, FeedResponse, HashtagCount } from '$lib/types';
let uploads = $state<FeedUpload[]>([]);
@@ -152,11 +153,7 @@
if (u) selectedUpload = u;
}
async function handleLogout() {
try { await api.delete('/session'); } catch { /* ignore */ }
clearAuth();
goto('/join');
}
</script>
<div class="min-h-screen bg-gray-50">
@@ -171,12 +168,15 @@
>
Hochladen
</a>
<button
onclick={handleLogout}
<a
href="/account"
class="text-sm text-gray-500 hover:text-gray-700"
aria-label="Mein Konto"
>
Abmelden
</button>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z" />
</svg>
</a>
</div>
</div>
@@ -224,3 +224,6 @@
onlike={handleLike}
/>
{/if}
<!-- First-visit onboarding guide -->
<OnboardingGuide />

View File

@@ -10,6 +10,13 @@
let pin = $state('');
let copied = $state(false);
// Name-taken state — shown instead of the normal form
let nameTaken = $state(false);
let takenName = $state('');
let recoveryPin = $state('');
let recoveryError = $state('');
let recoveryLoading = $state(false);
async function handleJoin() {
if (!displayName.trim()) return;
loading = true;
@@ -22,11 +29,14 @@
is_new: boolean;
}>('/join', { display_name: displayName.trim() });
setAuth(res.jwt, res.pin, res.user_id);
setAuth(res.jwt, res.pin, res.user_id, displayName.trim());
pin = res.pin;
showPinModal = true;
} catch (e) {
if (e instanceof ApiError) {
if (e instanceof ApiError && e.code === 'conflict') {
takenName = displayName.trim();
nameTaken = true;
} else if (e instanceof ApiError) {
error = e.message;
} else {
error = 'Ein Fehler ist aufgetreten.';
@@ -36,6 +46,35 @@
}
}
async function handleInlineRecover() {
if (recoveryPin.length < 4) return;
recoveryLoading = true;
recoveryError = '';
try {
const res = await api.post<{ jwt: string; user_id: string }>(
'/recover',
{ display_name: takenName, pin: recoveryPin.trim() }
);
setAuth(res.jwt, recoveryPin.trim(), res.user_id, takenName);
goto('/feed');
} catch (e) {
if (e instanceof ApiError) {
recoveryError = e.message;
} else {
recoveryError = 'Ein Fehler ist aufgetreten.';
}
} finally {
recoveryLoading = false;
}
}
function tryDifferentName() {
nameTaken = false;
recoveryPin = '';
recoveryError = '';
// Keep displayName so the user can edit it slightly
}
function copyPin() {
navigator.clipboard.writeText(pin);
copied = true;
@@ -49,35 +88,85 @@
<div class="flex min-h-screen items-center justify-center bg-gray-50 px-4">
<div class="w-full max-w-sm">
<h1 class="mb-2 text-center text-2xl font-bold text-gray-900">Willkommen!</h1>
<p class="mb-6 text-center text-gray-600">Gib deinen Namen ein, um dem Event beizutreten.</p>
<form onsubmit={(e) => { e.preventDefault(); handleJoin(); }}>
<input
type="text"
bind:value={displayName}
placeholder="Dein Name"
maxlength={50}
class="mb-3 w-full rounded-lg border border-gray-300 px-4 py-3 text-lg focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
/>
{#if nameTaken}
<!-- Name-taken state: sign in with PIN or choose a different name -->
<div class="mb-5 rounded-lg border border-amber-200 bg-amber-50 p-4">
<p class="font-semibold text-amber-900">{takenName}" ist bereits vergeben.</p>
<p class="mt-1 text-sm text-amber-800">
Wähle einen anderen Namen, z.&nbsp;B. einen Spitznamen oder füge deinen Nachnamen hinzu
(„{takenName} M." oder „{takenName} aus Berlin").
</p>
</div>
{#if error}
<p class="mb-3 text-sm text-red-600">{error}</p>
{/if}
<p class="mb-3 text-sm font-medium text-gray-700">
Falls du das bist, melde dich mit deinem PIN an:
</p>
<form onsubmit={(e) => { e.preventDefault(); handleInlineRecover(); }}>
<input
type="text"
bind:value={recoveryPin}
placeholder="4-stelliger PIN"
maxlength={4}
inputmode="numeric"
pattern="[0-9]*"
class="mb-3 w-full rounded-lg border border-gray-300 px-4 py-3 text-center text-2xl font-mono tracking-widest focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
/>
{#if recoveryError}
<p class="mb-3 text-sm text-red-600">{recoveryError}</p>
{/if}
<button
type="submit"
disabled={recoveryLoading || recoveryPin.length < 4}
class="mb-3 w-full rounded-lg bg-blue-600 px-4 py-3 font-medium text-white transition hover:bg-blue-700 disabled:opacity-50"
>
{recoveryLoading ? 'Wird angemeldet...' : 'Anmelden'}
</button>
</form>
<button
type="submit"
disabled={loading || !displayName.trim()}
class="w-full rounded-lg bg-blue-600 px-4 py-3 text-lg font-medium text-white transition hover:bg-blue-700 disabled:opacity-50"
onclick={tryDifferentName}
class="w-full rounded-lg border border-gray-300 px-4 py-3 font-medium text-gray-700 transition hover:bg-gray-50"
>
{loading ? 'Wird geladen...' : 'Beitreten'}
Anderen Namen wählen
</button>
</form>
<p class="mt-4 text-center text-sm text-gray-500">
Schon dabei?
<a href="/recover" class="text-blue-600 hover:underline">Mit PIN wiederherstellen</a>
</p>
{:else}
<!-- Normal join form -->
<h1 class="mb-2 text-center text-2xl font-bold text-gray-900">Willkommen!</h1>
<p class="mb-6 text-center text-gray-600">Gib deinen Namen ein, um dem Event beizutreten.</p>
<form onsubmit={(e) => { e.preventDefault(); handleJoin(); }}>
<input
type="text"
bind:value={displayName}
placeholder="Dein Name"
maxlength={50}
class="mb-3 w-full rounded-lg border border-gray-300 px-4 py-3 text-lg focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
/>
{#if error}
<p class="mb-3 text-sm text-red-600">{error}</p>
{/if}
<button
type="submit"
disabled={loading || !displayName.trim()}
class="w-full rounded-lg bg-blue-600 px-4 py-3 text-lg font-medium text-white transition hover:bg-blue-700 disabled:opacity-50"
>
{loading ? 'Wird geladen...' : 'Beitreten'}
</button>
</form>
<p class="mt-4 text-center text-sm text-gray-500">
Schon dabei?
<a href="/recover" class="text-blue-600 hover:underline">Mit PIN wiederherstellen</a>
</p>
{/if}
</div>
</div>

View File

@@ -25,7 +25,7 @@
user_id: string;
}>('/recover', { display_name: displayName.trim(), pin: pin.trim() });
setAuth(res.jwt, pin.trim(), res.user_id);
setAuth(res.jwt, pin.trim(), res.user_id, displayName.trim());
goto('/feed');
} catch (e) {
if (e instanceof ApiError) {

View File

@@ -3,5 +3,11 @@ import tailwindcss from '@tailwindcss/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [tailwindcss(), sveltekit()]
plugins: [tailwindcss(), sveltekit()],
server: {
proxy: {
'/api': 'http://localhost:3000',
'/media': 'http://localhost:3000'
}
}
});