Files
Andrew S Erwin eff81e4d8d Settings: remove the Contacts sync tab; the sync API remains
The single-config Nextcloud Contacts sync tab is gone — the unified
Nextcloud tab is the UI path for connecting an account. POST
/api/contacts/sync is untouched (Contact rows still feed contact-linking;
the handler is stateless, so no persisted config orphans). Legacy
?tab=nextcloud deep links map to the unified tab on first render and clean
the URL; CardDAV/help wording follows. Regression asserts the tab is gone
and the legacy deep link lands on the Nextcloud form.
2026-11-23 16:09:17 -06:00

301 lines
16 KiB
TypeScript

'use client'
// Settings → CardDAV: connect external CardDAV address books (any RFC 6352
// service). Each server address book materializes as its own Collection
// whose members are bookmarks — one per contact, carrying the card's DAV
// .vcf URL — refreshed by the background engine and on demand via Sync.
// House disciplines, identical to the WebDAV/CalDAV siblings: passwords are
// write-only (never prefilled; the mask round-trips unchanged), every
// mutating PATCH carries the row version (409 reloads), and plan or dial
// failures surface the server's message — the UI never guesses. When the
// deployment serves NEXTCLOUD_URL (the Core shape), the list arrives with a
// ready-made suggestion; the prefill composes the address-book home with
// the username so the URL shown is the URL saved.
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 { Switch } from '@/components/ui/switch'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { AlertTriangle, BookUser, Cloud, FlaskConical, Loader2, Plus, RefreshCw, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import { SafeDate } from '@/components/safe-format'
const KEY_MASK = '••••••••'
type AddressbookRef = { href: string; name: string; collectionId: string | null }
type CardDavConnection = {
id: string; name: string; url: string; username: string
secret: string; enabled: boolean; addressbooks: AddressbookRef[]
lastSyncedAt: string | null; lastError: string | null; version: number
}
type Suggestion = { kind: string; name: string; url: string }
type TestResult = { ok: boolean; addressbooks?: string[]; error?: string }
type SyncResult = { ok: boolean; books?: number; cards?: number; created?: number; reused?: number; updated?: number; kept?: number; removed?: number; truncated?: boolean; error?: string }
type FormState = {
id: string | null; version: number
name: string; url: string; username: string
password: string; hasStoredSecret: boolean
}
const emptyForm: FormState = { id: null, version: 0, name: '', url: '', username: '', password: '', hasStoredSecret: false }
async function api(path: string, init?: RequestInit): Promise<Response> {
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
}
export function CardDavSettings() {
const { data: session } = useSession()
const [connections, setConnections] = useState<CardDavConnection[]>([])
const [suggestions, setSuggestions] = useState<Suggestion[]>([])
const [allowed, setAllowed] = useState(true)
const [loading, setLoading] = useState(true)
const [form, setForm] = useState<FormState | null>(null)
const [saving, setSaving] = useState(false)
const [testing, setTesting] = useState<string | null>(null)
const [syncing, setSyncing] = useState<string | null>(null)
const [results, setResults] = useState<Record<string, { test?: TestResult; sync?: SyncResult }>>({})
const reload = useCallback(() =>
api('/api/carddav/connections')
.then(r => r.json())
.then(data => {
setConnections(Array.isArray(data?.connections) ? data.connections : [])
setSuggestions(Array.isArray(data?.suggestions) ? data.suggestions : [])
setAllowed(data?.allowed === true)
})
.catch(() => toast.error('Could not load CardDAV connections'))
.finally(() => setLoading(false)), [])
useEffect(() => { reload() }, [reload])
const openCreate = () => setForm({ ...emptyForm })
const openSuggestion = (s: Suggestion) => {
const email = session?.user?.email ?? ''
const username = email ? email.split('@')[0] : ''
// Compose visibly: the suggestion hands us the address-book home
// prefix, so the URL in the form is already the URL that gets saved.
setForm({ ...emptyForm, name: s.name, username, url: username ? s.url + username + '/' : s.url })
}
const openEdit = (c: CardDavConnection) => setForm({
id: c.id, version: c.version, name: c.name, url: c.url, username: c.username,
password: '', hasStoredSecret: c.secret === KEY_MASK,
})
const save = async () => {
if (!form) return
const body: Record<string, unknown> = {
name: form.name.trim(), url: form.url.trim(), username: form.username.trim(),
}
// Write-only password: send only what the user typed; the mask (or an
// empty field) tells the server to keep the stored value.
if (form.password) body.password = form.password
setSaving(true)
try {
const res = form.id
? await api(`/api/carddav/connections/${form.id}`, { method: 'PATCH', body: JSON.stringify({ ...body, version: form.version }) })
: await api('/api/carddav/connections', { method: 'POST', body: JSON.stringify(body) })
const data = await res.json().catch(() => null)
if (res.status === 409) {
toast.error('Connection changed elsewhere — reloaded')
await reload()
setForm(null)
return
}
if (!res.ok) { toast.error(data?.error ?? 'Could not save the connection'); return }
toast.success(form.id ? 'Connection updated' : 'Address book connected — sync it to materialize the collections')
setForm(null)
await reload()
} catch { toast.error('Could not save the connection') }
finally { setSaving(false) }
}
const test = async (c: CardDavConnection) => {
setTesting(c.id)
try {
const res = await api(`/api/carddav/connections/${c.id}/test`, { method: 'POST', body: '{}' })
const data = await res.json().catch(() => null)
setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], test: (data as TestResult) ?? { ok: false, error: 'Network error' } } }))
if (data?.ok) toast.success(`${data.addressbooks?.length ?? 0} address book${data.addressbooks?.length === 1 ? '' : 's'} found`)
} catch { setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], test: { ok: false, error: 'Network error' } } })) }
finally { setTesting(null) }
}
const sync = async (c: CardDavConnection) => {
setSyncing(c.id)
try {
const res = await api(`/api/carddav/connections/${c.id}/sync`, { method: 'POST', body: '{}' })
const data = await res.json().catch(() => null)
setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], sync: (data as SyncResult) ?? { ok: false, error: 'Network error' } } }))
if (data?.ok) toast.success(`Synced ${data.cards} contact${data.cards === 1 ? '' : 's'} from ${data.books} address book${data.books === 1 ? '' : 's'}`)
await reload()
} catch { setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], sync: { ok: false, error: 'Network error' } } })) }
finally { setSyncing(null) }
}
const toggle = async (c: CardDavConnection) => {
const res = await api(`/api/carddav/connections/${c.id}`, {
method: 'PATCH', body: JSON.stringify({ enabled: !c.enabled, version: c.version }),
})
if (res.status === 409) { toast.error('Connection changed elsewhere — reloaded'); await reload(); return }
if (!res.ok) { toast.error((await res.json().catch(() => null))?.error ?? 'Could not update'); return }
await reload()
}
const remove = async (c: CardDavConnection) => {
const res = await api(`/api/carddav/connections/${c.id}`, { method: 'DELETE' })
if (res.ok) { toast.success(`Removed ${c.name} — the address book collections and their bookmarks stay`); await reload() }
else toast.error((await res.json().catch(() => null))?.error ?? 'Could not remove')
}
if (loading) {
return (
<div className="rounded-lg border p-4 flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Loading CardDAV connections…
</div>
)
}
return (
<div className="rounded-lg border p-4 space-y-4">
<div className="flex items-start justify-between gap-3">
<div>
<h3 className="font-medium flex items-center gap-2"><BookUser className="h-4 w-4" /> CardDAV address books</h3>
<p className="text-sm text-muted-foreground mt-1">
Connect an address book from any CardDAV service. Each book becomes a Collection, one
bookmark per contact, re-checked in the background every 30 minutes. Passwords are
encrypted at rest and never shown again. (This is separate from the Contacts page,
which feeds contact-linking.)
</p>
</div>
{allowed && <Button size="sm" onClick={openCreate}><Plus className="h-4 w-4 mr-1" /> Connect address book</Button>}
</div>
{!allowed && (
<div className="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs">
<AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" />
<p>CardDAV address books are not available on your current plan. Existing connections stay but no longer sync.</p>
</div>
)}
{suggestions.length > 0 && allowed && (
<div className="space-y-2">
{suggestions.map(s => (
<div key={s.kind} className="flex items-center gap-3 rounded-md border border-dashed p-3">
<Cloud className="h-5 w-5 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">{s.name} detected on this server</p>
<p className="truncate text-xs text-muted-foreground font-mono">{s.url}</p>
</div>
<Button size="sm" variant="outline" onClick={() => openSuggestion(s)}>Use</Button>
</div>
))}
</div>
)}
{connections.length === 0 ? (
<p className="text-sm text-muted-foreground">No CardDAV address books connected.</p>
) : (
<ul className="divide-y rounded-md border">
{connections.map(c => {
const r = results[c.id]
const failure = r?.sync && !r.sync.ok ? r.sync.error : r?.test && !r.test.ok ? r.test.error : null
return (
<li key={c.id} className="space-y-2 p-3">
<div className="flex flex-wrap items-center gap-2">
<Switch checked={c.enabled} onCheckedChange={() => toggle(c)} aria-label={`Enable ${c.name}`} />
<span className="min-w-[6rem] flex-1 truncate text-sm font-medium">{c.name}</span>
{Array.isArray(c.addressbooks) && c.addressbooks.length > 0 && <Badge variant="outline" className="shrink-0 text-[10px]">{c.addressbooks.length} books</Badge>}
<span className="ml-auto flex items-center gap-1">
<Button size="sm" variant="outline" onClick={() => sync(c)} loading={syncing === c.id} aria-label={`Sync ${c.name}`}>
<RefreshCw className="h-3.5 w-3.5 mr-1" /> Sync
</Button>
<Button size="sm" variant="outline" onClick={() => test(c)} loading={testing === c.id} aria-label={`Test ${c.name}`}>
<FlaskConical className="h-3.5 w-3.5 mr-1" /> Test
</Button>
<Button size="sm" variant="ghost" onClick={() => openEdit(c)}>Edit</Button>
<Button size="sm" variant="ghost" onClick={() => remove(c)} aria-label={`Remove ${c.name}`}>
<Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" />
</Button>
</span>
</div>
<p className="text-xs text-muted-foreground font-mono truncate">{c.username}@{c.url}</p>
{Array.isArray(c.addressbooks) && c.addressbooks.length > 0 && (
<p className="text-xs text-muted-foreground">
Books: {c.addressbooks.map(k => k.name).join(', ')}
</p>
)}
<p className="text-xs text-muted-foreground">
{c.lastSyncedAt
? <>Last synced <SafeDate date={c.lastSyncedAt} localize /></>
: 'Not synced yet — use Sync to materialize the collections'}
</p>
{!failure && c.lastError && (
<p className="rounded-md bg-destructive/10 p-2 text-xs text-destructive">{c.lastError}</p>
)}
{failure && <p className="rounded-md bg-destructive/10 p-2 text-xs text-destructive">{failure}</p>}
{r?.sync?.ok && (
<p className="rounded-md bg-muted/50 p-2 text-xs text-muted-foreground">
{r.sync.cards} contacts across {r.sync.books ?? 0} books: {r.sync.created ?? 0} created, {r.sync.reused ?? 0} reused,{" "}
{r.sync.updated ?? 0} changed, {r.sync.removed ?? 0} detached
{r.sync.truncated && ' — a listing was capped; nothing was treated as deleted'}
</p>
)}
{r?.test?.ok && (
<p className="rounded-md bg-muted/50 p-2 text-xs text-muted-foreground">
Found: {r.test.addressbooks?.join(', ') || 'no address books'}
</p>
)}
</li>
)
})}
</ul>
)}
<Dialog open={form !== null} onOpenChange={(open) => { if (!open) setForm(null) }}>
<DialogContent className="max-w-lg">
<DialogHeader><DialogTitle>{form?.id ? 'Edit CardDAV connection' : 'Connect a CardDAV address book'}</DialogTitle></DialogHeader>
{form && (
<div className="space-y-3">
<div>
<label className="text-xs font-medium">Name</label>
<Input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="e.g. House contacts" maxLength={100} />
</div>
<div>
<label className="text-xs font-medium">Address book URL</label>
<Input value={form.url} onChange={e => setForm({ ...form, url: e.target.value })} placeholder="https://cloud.example.com/remote.php/dav/addressbooks/users/username/contacts" />
<p className="mt-1 text-xs text-muted-foreground">One address book or a home holding several, on an https endpoint (CardDAV credentials never travel to other ports or plaintext). Discovery is network-guarded and never follows redirects.</p>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs font-medium">Username</label>
<Input value={form.username} onChange={e => setForm({ ...form, username: e.target.value })} placeholder="erwin" maxLength={200} />
</div>
<div>
<label className="text-xs font-medium">Password {form.hasStoredSecret ? '(unchanged)' : ''}</label>
<Input
type="password"
value={form.password}
onChange={e => setForm({ ...form, password: e.target.value })}
placeholder={form.hasStoredSecret ? `${KEY_MASK} (leave blank to keep)` : 'Account or app password'}
maxLength={2000}
/>
</div>
</div>
{form.hasStoredSecret && <p className="text-xs text-muted-foreground">Stored credentials are never shown; blank keeps the current one.</p>}
<p className="text-xs text-muted-foreground">Tip: services that use two-factor login usually need an app password here (in Nextcloud: Settings → Security → Devices).</p>
<div className="flex justify-end gap-2 pt-1">
<Button variant="outline" onClick={() => setForm(null)}>Cancel</Button>
<Button onClick={save} loading={saving}>{form.id ? 'Save changes' : 'Connect address book'}</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
)
}