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([]); export const isProcessing = writable(false); /** Set to the timestamp (ms) at which the rate-limit lifts, or null when clear. */ export const rateLimitRetryAt = writable(null); const DB_NAME = 'eventsnap-uploads'; const STORE_NAME = 'queue'; let db: IDBPDatabase | null = null; async function getDb(): Promise { 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 { 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 { 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 { 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 { 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 { const database = await getDb(); await database.delete(STORE_NAME, id); queueItems.update((items) => items.filter((item) => item.id !== id)); } export async function clearCompleted(): Promise { 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 { 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 { 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((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 ) ); }