'use client' // Settings → Nextcloud: ONE credential entry connects files (WebDAV), // calendars (CalDAV) and contacts (CardDAV) at once. The server composes // the per-user DAV roots, verifies the credential against each protocol // and stores ordinary sibling connections — this tab orchestrates, then // fires the existing /sync surfaces so collections materialize immediately. // House disciplines: the password is write-only (never prefilled, cleared // after submit), plan gates and failures surface the server's message // verbatim (the UI never guesses entitlements), and partial success is a // first-class outcome — a carddav-only plan still connects contacts. // Ongoing management stays in the per-protocol tabs; the separate Contacts // sync (Contact rows) is a different feature and is untouched. import { useCallback, useEffect, useState } from 'react' import { useSession } from 'next-auth/react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Badge } from '@/components/ui/badge' import { AlertTriangle, BookUser, CalendarDays, Cloud, FolderSync, Loader2, RefreshCw } from 'lucide-react' import { toast } from 'sonner' import { SafeDate } from '@/components/safe-format' type Connection = { id: string; name: string; url: string; username: string enabled: boolean; lastSyncedAt: string | null; lastError: string | null } type Part = { allowed: boolean; connections: Connection[] } type Status = { origin: string; files: Part; calendars: Part; contacts: Part } type ConnectResult = { status: 'created' | 'exists' | 'gated' | 'error'; id?: string; name?: string; url?: string; error?: string } type SyncResult = { ok: boolean; files?: number; calendars?: number; events?: number; books?: number; cards?: number; created?: number; error?: string } const CONNECTORS = [ { key: 'files' as const, label: 'Files', proto: 'webdav', tab: 'webdav', icon: FolderSync, hint: 'One Collection, one bookmark per file.' }, { key: 'calendars' as const, label: 'Calendars', proto: 'caldav', tab: 'caldav', icon: CalendarDays, hint: 'One Collection per server calendar, one bookmark per event.' }, { key: 'contacts' as const, label: 'Contacts', proto: 'carddav', tab: 'carddav', icon: BookUser, hint: 'One Collection per address book, one bookmark per contact.' }, ] async function api(path: string, init?: RequestInit): Promise { return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) } export function NextcloudSettings({ onManage }: { onManage?: (tab: string) => void }) { const { data: session } = useSession() const [status, setStatus] = useState(null) const [loading, setLoading] = useState(true) const [url, setUrl] = useState('') const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [connecting, setConnecting] = useState(false) const [results, setResults] = useState | null>(null) const [syncs, setSyncs] = useState>({}) const emailLocal = (session?.user?.email ?? '').split('@')[0] const reload = useCallback(() => api('/api/nextcloud/status') .then(r => r.json()) .then((data: Status) => { setStatus(data) // Prefill the deployment's origin hint (Core) and the viewer's email // local-part once; the person can still edit both fields. setUrl(prev => prev || data?.origin || '') setUsername(prev => prev || emailLocal) }) .catch(() => toast.error('Could not load Nextcloud status')) .finally(() => setLoading(false)), [emailLocal]) useEffect(() => { reload() }, [reload]) const connect = async () => { setConnecting(true) setResults(null) setSyncs({}) try { const res = await api('/api/nextcloud/connect', { method: 'POST', body: JSON.stringify({ url: url.trim(), username: username.trim(), password }), }) const data = await res.json().catch(() => null) if (!res.ok) { toast.error(data?.error ?? 'Could not connect'); return } const results = (data?.results ?? {}) as Record setResults(results) setPassword('') // write-only: never keep the plaintext around const created = CONNECTORS.filter(c => results[c.key]?.status === 'created') if (created.length === 0) { toast.success('Nextcloud account processed') } else { toast.success(`${created.length} connection${created.length === 1 ? '' : 's'} created — syncing`) } // Materialize through the EXISTING per-protocol sync surfaces, in // parallel — their limiters, budgets and timeouts stay authoritative. setSyncs(Object.fromEntries(created.map(c => [c.key, 'pending' as const]))) await Promise.allSettled(created.map(async c => { const id = results[c.key].id try { const sr = await api(`/api/${c.proto}/connections/${id}/sync`, { method: 'POST', body: '{}' }) const sd = await sr.json().catch(() => null) setSyncs(prev => ({ ...prev, [c.key]: (sd as SyncResult) ?? { ok: false, error: 'Network error' } })) } catch { setSyncs(prev => ({ ...prev, [c.key]: { ok: false, error: 'Network error' } })) } })) await reload() } catch { toast.error('Could not connect') } finally { setConnecting(false) } } if (loading || !status) { return (
Loading Nextcloud status…
) } const allGated = CONNECTORS.every(c => !status[c.key].allowed) return (

Nextcloud

Connect your Nextcloud account once — files, calendars and contacts become Collections of bookmarks, re-checked in the background every 30 minutes. The password is encrypted at rest and never shown again.

{allGated && (

Nextcloud connections are not available on your current plan.

)} {!allGated && (
setUrl(e.target.value)} placeholder="https://cloud.example.com" maxLength={2048} />

Your Nextcloud origin{status.origin ? ' — suggested by this deployment' : ''}. A pasted DAV link works too.

setUsername(e.target.value)} placeholder="erwin" maxLength={200} />
setPassword(e.target.value)} placeholder="Account or app password" maxLength={2000} />

Tip: with two-factor login, create an app password in Nextcloud (Settings → Security → Devices). Each part connects only if your plan includes it.

)} {results && (
    {CONNECTORS.map(c => { const r = results[c.key] if (!r) return null const sync = syncs[c.key] return (
  • {c.label} {r.status === 'created' && connected} {r.status === 'exists' && already connected} {r.status === 'gated' && plan} {r.status === 'error' && failed} {onManage && (r.status === 'created' || r.status === 'exists') && ( )}
    {r.status === 'gated' &&

    {r.error}

    } {r.status === 'error' &&

    {r.error}

    } {r.status === 'created' && sync === 'pending' && (

    Syncing…

    )} {r.status === 'created' && sync && sync !== 'pending' && ( sync.ok ?

    {syncSummary(c.key, sync)}

    :

    {sync.error ?? 'Sync failed'} — retry from the {c.label} tab.

    )} {r.status === 'exists' &&

    Kept the existing connection; sync it from the {c.label} tab.

    }
  • ) })}
)}
{CONNECTORS.map(c => { const part = status[c.key] return (
{c.label} {!part.allowed && not on your plan} {onManage && part.connections.length > 0 && ( )}

{c.hint}

{part.connections.length === 0 ?

Not connected yet.

: (
    {part.connections.map(conn => (
  • {conn.name} {' — '}{conn.lastSyncedAt ? <>last synced : 'not synced yet'} {conn.lastError &&

    {conn.lastError}

    }
  • ))}
)}
) })}
) } function syncSummary(key: 'files' | 'calendars' | 'contacts', s: SyncResult): string { const created = s.created ? ` (${s.created} new)` : '' if (key === 'files') return `${s.files ?? 0} files${created}` if (key === 'calendars') return `${s.events ?? 0} events across ${s.calendars ?? 0} calendars${created}` return `${s.cards ?? 0} contacts in ${s.books ?? 0} address books${created}` }