Something went wrong. Try again.
An experimental Wallabag client
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200import { getSettings, saveSettings, clearAuth } from '../db/queries';import type { Settings } from '../db/schema';
export class AuthError extends Error { constructor(message: string) { super(message); this.name = 'AuthError'; }}
export class ApiError extends Error { constructor( message: string, public status: number ) { super(message); this.name = 'ApiError'; }}
function proxyUrl(settings: Settings, path: string): string { const target = encodeURIComponent(`${settings.wallabag_url}${path}`); return `${settings.worker_url}/proxy?target=${target}`;}
async function refreshToken(settings: Settings): Promise<Settings> { if (!settings.refresh_token) throw new AuthError('No refresh token');
const resp = await fetch(proxyUrl(settings, '/oauth/v2/token'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ grant_type: 'refresh_token', refresh_token: settings.refresh_token, client_id: settings.client_id, client_secret: settings.client_secret }) });
if (!resp.ok) { await clearAuth(); if (typeof window !== 'undefined') { window.dispatchEvent(new Event('mathom:auth-cleared')); } throw new AuthError('Token refresh failed — re-authentication required'); }
const data = await resp.json(); const updated: Partial<Settings> = { access_token: data.access_token, refresh_token: data.refresh_token ?? settings.refresh_token, token_expires_at: Date.now() + data.expires_in * 1000 }; await saveSettings(updated); return { ...settings, ...updated };}
async function getValidSettings(): Promise<Settings> { const settings = await getSettings(); if (!settings?.access_token) throw new AuthError('Not authenticated');
// Refresh if token expires in less than 60 seconds if (settings.token_expires_at && settings.token_expires_at - Date.now() < 60_000) { return refreshToken(settings); } return settings;}
async function apiFetch(path: string, init?: RequestInit): Promise<Response> { let settings = await getValidSettings();
const doFetch = (s: Settings) => fetch(proxyUrl(s, path), { ...init, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${s.access_token}`, ...init?.headers } });
let resp = await doFetch(settings);
if (resp.status === 401) { settings = await refreshToken(settings); resp = await doFetch(settings); }
if (!resp.ok) throw new ApiError(`API error: ${resp.status} ${resp.statusText}`, resp.status); return resp;}
export async function authenticate( wallabag_url: string, worker_url: string, client_id: string, client_secret: string, username: string, password: string): Promise<void> { const target = encodeURIComponent(`${wallabag_url}/oauth/v2/token`); const resp = await fetch(`${worker_url}/proxy?target=${target}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ grant_type: 'password', client_id, client_secret, username, password }) });
if (!resp.ok) { const body = await resp.text().catch(() => ''); throw new AuthError(`Authentication failed: ${resp.status} ${body}`); }
const data = await resp.json(); await saveSettings({ wallabag_url, worker_url, client_id, client_secret, access_token: data.access_token, refresh_token: data.refresh_token, token_expires_at: Date.now() + data.expires_in * 1000 });}
export interface WallabagEntry { id: number; title: string; url: string; origin_url: string | null; content: string; preview_picture: string | null; domain_name: string; reading_time: number; language: string | null; is_archived: 0 | 1; is_starred: 0 | 1; created_at: string; updated_at: string; published_at: string | null; tags: Array<{ id: number; label: string; slug: string }>;}
export async function fetchEntries(since: number, page = 1, perPage = 30): Promise<{ entries: WallabagEntry[]; pages: number;}> { const resp = await apiFetch( `/api/entries?since=${since}&page=${page}&perPage=${perPage}&detail=full` ); const data = await resp.json(); return { entries: data._embedded?.items ?? [], pages: data.pages ?? 1 };}
export async function patchEntry( id: number, patch: Record<string, unknown>): Promise<WallabagEntry> { const resp = await apiFetch(`/api/entries/${id}`, { method: 'PATCH', body: JSON.stringify(patch) }); return resp.json();}
export async function deleteEntryApi(id: number): Promise<void> { await apiFetch(`/api/entries/${id}`, { method: 'DELETE' });}
export async function addEntry(url: string): Promise<WallabagEntry> { const resp = await apiFetch('/api/entries', { method: 'POST', body: JSON.stringify({ url }) }); return resp.json();}
export async function searchEntries( term: string, page = 1, perPage = 30): Promise<{ entries: WallabagEntry[]; pages: number }> { const resp = await apiFetch( `/api/search?term=${encodeURIComponent(term)}&page=${page}&perPage=${perPage}` ); const data = await resp.json(); return { entries: data._embedded?.items ?? [], pages: data.pages ?? 1 };}