Files
EventSnap/frontend/src/lib/upload-queue.ts
MechaCat02 251f9f1469 frontend(plumbing): shared theme tokens, cross-cutting stores, gestures, sheets
The plumbing layer the v0.16 UI features (and dark mode) build on.

Shared design tokens (Tailwind v4):
- tailwind-theme.css (new): @custom-variant dark (class-driven, beats OS
  default) + @theme color/font/radius tokens + baseline html/html.dark
  rules so any page that hasn't been re-themed still renders the right
  body bg + color-scheme.
- src/app.css + export-viewer/src/app.css now import the shared theme.
- src/app.html: 6-line FOUC guard sets <html class="dark"> before paint
  (mirrored from theme-store.ts) so dark reloads no longer flash white.
  Adds <meta name="theme-color"> kept in sync by initTheme().

Cross-cutting stores (one per concern, per docs/FEATURES §2.9):
- data-mode-store.ts: 'saver' | 'original' per-device, plus pickMediaUrl
  helper so feed cards / lightbox / diashow all resolve URLs the same way.
- privacy-note-store.ts: hydrated from /me/context, refreshed on SSE
  event-updated.
- quota-store.ts: { enabled, used, limit, active_uploaders, free_disk },
  refreshed after each upload completes.
- theme-store.ts: 'system' | 'light' | 'dark' preference + derived
  appliedTheme + initTheme() that syncs <html class>, localStorage,
  and the theme-color meta. Listens to prefers-color-scheme.
- auth.ts: currentPin writable mirror + clearPin() helper called from
  the global pin-reset SSE handler — fixes the stale-PIN bug where the
  localStorage copy survived a reset.

DTO mirror:
- types.ts: QuotaDto, MeContextDto, PinResetResponse, DeltaResponse each
  carry a `// mirrors backend/...` comment per the lib README convention.

SSE client:
- sse.ts: KNOWN_EVENTS registry (one entry per server-emitted type),
  synthetic feed-delta dispatched after foreground reconnect via the
  /feed/delta?since= endpoint, exponential backoff (1 → 60 s + jitter)
  on errors, attempt counter reset on user-initiated visibility resume.

Upload queue:
- upload-queue.ts: IDB schema bumped to v2 — entries tagged with userId;
  loadQueue filters by current user (no cross-user leak on shared
  devices); uploadItem refuses to upload an entry whose userId differs
  from getUserId() (defense-in-depth); new clearQueue() called on
  explicit logout. v2 upgrade wipes pre-v2 entries (no userId, can't
  attribute safely).

Mobile primitives:
- actions/longpress.ts: 500 ms hold with 10 px move tolerance, swallows
  the next click + the right-click contextmenu so the gesture doesn't
  double-fire the inner button's onclick.
- actions/doubletap.ts: tap-pair detector that preventDefaults the
  second tap so iOS Safari doesn't also zoom on double-tap.
- components/ContextSheet.svelte: generic bottom sheet driven by a
  ContextAction[] prop. Reused by feed posts, comments, host user rows.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 14:32:37 +02:00

318 lines
8.7 KiB
TypeScript

import { openDB, type IDBPDatabase } from 'idb';
import { writable, get } from 'svelte/store';
import { getToken, getUserId } from './auth';
import { refreshQuota } from './quota-store';
export interface QueueItem {
id: string;
userId: string;
fileName: string;
fileSize: number;
mimeType: string;
caption: string;
hashtags: string;
status: 'pending' | 'uploading' | 'done' | 'error';
progress: number;
error?: string;
}
// Store does NOT hold file blobs — those stay in IndexedDB only
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';
let db: IDBPDatabase | null = null;
async function getDb(): Promise<IDBPDatabase> {
if (db) return db;
// v1 → v2: add `userId` index so each guest's queue is isolated on shared devices.
// Pre-existing entries (no userId) are dropped on upgrade; nothing useful was ever
// persisted across logouts before this version.
db = await openDB(DB_NAME, 2, {
upgrade(database, oldVersion) {
if (oldVersion < 1) {
database.createObjectStore(STORE_NAME, { keyPath: 'id' });
}
if (oldVersion < 2) {
// Wipe any pre-v2 entries — they have no userId field and would belong
// to a now-indeterminate user. Safer to drop than to misattribute.
const tx = database.transaction(STORE_NAME, 'readwrite');
tx.objectStore(STORE_NAME).clear();
}
}
});
return db;
}
/**
* Wipe every queue entry — both IndexedDB rows and the in-memory store. Called on
* explicit logout so a second guest using the same device doesn't inherit (or be
* blamed for) the previous guest's pending uploads.
*/
export async function clearQueue(): Promise<void> {
const database = await getDb();
await database.clear(STORE_NAME);
queueItems.set([]);
rateLimitRetryAt.set(null);
}
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 myUserId = getUserId();
const all = await database.getAll(STORE_NAME);
// Only surface entries that belong to the current user. Entries from a previous
// guest on this device are filtered out (and would also be wiped on their next
// explicit logout via `clearQueue`).
const items: QueueItem[] = all
.filter((entry) => entry.userId && entry.userId === myUserId)
.map((entry) => ({
id: entry.id,
userId: entry.userId,
fileName: entry.fileName,
fileSize: entry.fileSize,
mimeType: entry.mimeType,
caption: entry.caption ?? '',
hashtags: entry.hashtags ?? '',
status: entry.status === 'uploading' ? 'pending' : entry.status,
progress: entry.status === 'done' ? 100 : 0,
error: entry.error
}));
queueItems.set(items);
}
export async function addToQueue(
file: File,
caption: string,
hashtags: string
): Promise<void> {
const database = await getDb();
const userId = getUserId();
if (!userId) return; // not authenticated — nothing to do
const id = crypto.randomUUID();
const entry = {
id,
userId,
fileName: file.name,
fileSize: file.size,
mimeType: file.type,
caption,
hashtags,
status: 'pending',
blob: file
};
await database.put(STORE_NAME, entry);
queueItems.update((items) => [
...items,
{
id,
userId,
fileName: file.name,
fileSize: file.size,
mimeType: file.type,
caption,
hashtags,
status: 'pending',
progress: 0
}
]);
processQueue();
}
export async function retryItem(id: string): Promise<void> {
const database = await getDb();
const entry = await database.get(STORE_NAME, id);
if (!entry) return;
entry.status = 'pending';
entry.error = undefined;
await database.put(STORE_NAME, entry);
queueItems.update((items) =>
items.map((item) =>
item.id === id ? { ...item, status: 'pending' as const, progress: 0, error: undefined } : item
)
);
processQueue();
}
export async function removeItem(id: string): Promise<void> {
const database = await getDb();
await database.delete(STORE_NAME, id);
queueItems.update((items) => items.filter((item) => item.id !== id));
}
export async function clearCompleted(): Promise<void> {
const database = await getDb();
const items = get(queueItems);
for (const item of items) {
if (item.status === 'done') {
await database.delete(STORE_NAME, item.id);
}
}
queueItems.update((items) => items.filter((item) => item.status !== 'done'));
}
let processing = false;
async function processQueue(): Promise<void> {
if (processing) return;
processing = true;
isProcessing.set(true);
try {
while (true) {
const items = get(queueItems);
const next = items.find((item) => item.status === 'pending');
if (!next) break;
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;
isProcessing.set(false);
}
}
async function uploadItem(id: string): Promise<void> {
const database = await getDb();
const entry = await database.get(STORE_NAME, id);
if (!entry || !entry.blob) {
updateItemStatus(id, 'error', 'Datei nicht gefunden.');
return;
}
const token = getToken();
const currentUserId = getUserId();
if (!token || !currentUserId) {
updateItemStatus(id, 'error', 'Nicht angemeldet.');
return;
}
// Defense-in-depth: if the device's signed-in user changed since this entry was
// queued, refuse to upload it under the new identity. `loadQueue` already filters
// by user; this guards the in-memory store path too.
if (entry.userId && entry.userId !== currentUserId) {
updateItemStatus(id, 'error', 'Anderer Nutzer angemeldet.');
return;
}
updateItemStatus(id, 'uploading');
try {
const formData = new FormData();
formData.append('file', entry.blob, entry.fileName);
if (entry.caption) formData.append('caption', entry.caption);
if (entry.hashtags) formData.append('hashtags', entry.hashtags);
await new Promise<void>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/v1/upload');
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const pct = Math.round((e.loaded / e.total) * 100);
queueItems.update((items) =>
items.map((item) => (item.id === id ? { ...item, progress: pct } : item))
);
}
});
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);
reject(new Error(body.message || `HTTP ${xhr.status}`));
} catch {
reject(new Error(`HTTP ${xhr.status}`));
}
}
});
xhr.addEventListener('error', () => reject(new Error('Netzwerkfehler')));
xhr.addEventListener('abort', () => reject(new Error('Abgebrochen')));
xhr.send(formData);
});
// Success — remove blob from IndexedDB, mark done
entry.status = 'done';
delete entry.blob;
await database.put(STORE_NAME, entry);
updateItemStatus(id, 'done');
// Refresh the per-user quota snapshot so the My Account widget reflects this
// upload's bytes without a manual reload.
void refreshQuota();
} 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;
await database.put(STORE_NAME, entry);
updateItemStatus(id, 'error', msg);
}
}
function updateItemStatus(
id: string,
status: QueueItem['status'],
error?: string
): void {
queueItems.update((items) =>
items.map((item) =>
item.id === id
? {
...item,
status,
progress: status === 'done' ? 100 : status === 'pending' ? 0 : item.progress,
error
}
: item
)
);
}