Something went wrong. Try again.
An experimental Wallabag client
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245import DOMPurify from 'dompurify';import { fetchEntries, patchEntry, deleteEntryApi, addEntry, searchEntries, type WallabagEntry} from '../api/client';import { upsertEntries, deleteEntry, saveSettings, getSettings, getPendingMutations, removeMutation, incrementMutationAttempt, getAllEntryIds, enqueueMutation, getEntries} from '../db/queries';import type { Entry } from '../db/schema';
function sanitizeEntry(raw: WallabagEntry): Entry { return { ...raw, content: DOMPurify.sanitize(raw.content ?? ''), cached_at: Date.now() };}
// Pure: extract image URLs from a set of entries. Used by the offline-prefetch// flow to feed the service worker's CacheFirst image route. We pull both the// preview thumbnail and any <img src> inside the sanitized article content.export function extractImageUrls(entries: Entry[]): string[] { const seen = new Set<string>(); for (const entry of entries) { if (entry.preview_picture && isHttpUrl(entry.preview_picture)) { seen.add(entry.preview_picture); } const matches = entry.content?.matchAll(/<img[^>]+src=["']([^"']+)["']/gi) ?? []; for (const m of matches) { if (isHttpUrl(m[1])) seen.add(m[1]); } } return [...seen];}
function isHttpUrl(candidate: string): boolean { try { const u = new URL(candidate); return u.protocol === 'http:' || u.protocol === 'https:'; } catch { return false; }}
// Browser-only: trigger an image-destination fetch so the SW's CacheFirst// image route caches it. Plain `fetch()` won't match because its `destination`// is empty; only `<img>` requests are tagged `image`.function prefetchImage(url: string): Promise<void> { return new Promise((resolve) => { const img = new Image(); const done = () => resolve(); img.onload = done; img.onerror = done; img.src = url; });}
export async function prefetchImageUrls( urls: string[], onProgress?: (done: number, total: number) => void): Promise<void> { const CONCURRENCY = 6; const queue = [...urls]; const total = urls.length; let done = 0; onProgress?.(0, total);
async function worker() { while (queue.length > 0) { const url = queue.shift(); if (!url) return; await prefetchImage(url); done++; onProgress?.(done, total); } }
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, total) }, () => worker()));}
export interface PrefetchResult { entries: number; images: number;}
export async function prefetchUnreadForOffline( onProgress?: (done: number, total: number) => void): Promise<PrefetchResult> { const entries = await getEntries('unread'); const urls = extractImageUrls(entries); await prefetchImageUrls(urls, onProgress); return { entries: entries.length, images: urls.length };}
export async function searchArticles(term: string): Promise<Entry[]> { const { entries } = await searchEntries(term); const sanitized = entries.map(sanitizeEntry); if (sanitized.length > 0) await upsertEntries(sanitized); return sanitized;}
export type AddArticleResult = { status: 'added'; entry: Entry } | { status: 'queued' };
export async function addArticleByUrl(url: string): Promise<AddArticleResult> { try { const raw = await addEntry(url); const entry = sanitizeEntry(raw); await upsertEntries([entry]); return { status: 'added', entry }; } catch { // Network or auth error — fall back to the mutation queue. The drainer will // retry and persist the resulting entry when connectivity returns. await enqueueMutation({ entry_id: 0, type: 'add', payload: { url } }); return { status: 'queued' }; }}
export async function syncIncremental(): Promise<{ synced: number }> { const settings = await getSettings(); const since = settings?.last_sync_at ?? 0;
let page = 1; let totalPages = 1; let synced = 0;
do { const { entries, pages } = await fetchEntries(since, page, 30); totalPages = pages;
if (entries.length > 0) { await upsertEntries(entries.map(sanitizeEntry)); synced += entries.length; } page++; } while (page <= totalPages);
await saveSettings({ last_sync_at: Math.floor(Date.now() / 1000) }); return { synced };}
export async function syncFull(): Promise<{ synced: number; deleted: number }> { const result = await syncIncremental();
// Full reconciliation: fetch all server IDs, remove orphaned local entries const localIds = new Set(await getAllEntryIds()); const serverIds = new Set<number>();
let page = 1; let totalPages = 1;
do { const { entries, pages } = await fetchEntries(0, page, 100); totalPages = pages; for (const e of entries) serverIds.add(e.id); page++; } while (page <= totalPages);
let deleted = 0; for (const id of localIds) { if (!serverIds.has(id)) { await deleteEntry(id); deleted++; } }
await saveSettings({ last_full_sync_at: Math.floor(Date.now() / 1000) }); return { ...result, deleted };}
const FULL_SYNC_INTERVAL_SECONDS = 24 * 60 * 60;
export async function maybeRunFullSync(): Promise<{ ran: boolean }> { const settings = await getSettings(); const last = settings?.last_full_sync_at ?? 0; const now = Math.floor(Date.now() / 1000); if (now - last < FULL_SYNC_INTERVAL_SECONDS) return { ran: false }; await syncFull(); return { ran: true };}
const BACKOFF_MS = [1000, 5000, 30000, 60000, 300000];
function backoffDelay(attempts: number): number { return BACKOFF_MS[Math.min(attempts, BACKOFF_MS.length - 1)];}
export async function drainMutationQueue(): Promise<void> { const mutations = await getPendingMutations();
for (const mutation of mutations) { if (mutation.attempts > 0) { const delay = backoffDelay(mutation.attempts); const elapsed = Date.now() - mutation.created_at; if (elapsed < delay) continue; }
try { switch (mutation.type) { case 'archive': await patchEntry(mutation.entry_id, { archive: 1 }); break; case 'unarchive': await patchEntry(mutation.entry_id, { archive: 0 }); break; case 'star': await patchEntry(mutation.entry_id, { starred: 1 }); break; case 'unstar': await patchEntry(mutation.entry_id, { starred: 0 }); break; case 'delete': await deleteEntryApi(mutation.entry_id); break; case 'add': { const raw = await addEntry((mutation.payload as { url: string }).url); await upsertEntries([sanitizeEntry(raw)]); break; } } await removeMutation(mutation.id!); } catch (err) { const errorMsg = err instanceof Error ? err.message : String(err); // Silently drop delete mutations for entries that are already gone if (mutation.type === 'delete' && errorMsg.includes('404')) { await removeMutation(mutation.id!); } else { await incrementMutationAttempt(mutation.id!, errorMsg); } } }}