import 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
inside the sanitized article content.
export function extractImageUrls(entries: Entry[]): string[] {
const seen = new Set();
for (const entry of entries) {
if (entry.preview_picture && isHttpUrl(entry.preview_picture)) {
seen.add(entry.preview_picture);
}
const matches = entry.content?.matchAll(/
]+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 `
` requests are tagged `image`.
function prefetchImage(url: string): Promise {
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 {
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 {
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 {
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 {
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();
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 {
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);
}
}
}
}