Two bugs made the suggested Nextcloud shares fail on Core: 1. Reachability: nextcloud.$DOMAIN is split-horizon DNS — inside the core network it answers the Nextcloud container's private IP, where nothing listens on 443 (traefik holds TLS on the public address), and netguard refuses private dials anyway. Verified from the core network: the private route refuses connections; the public route answers PROPFIND with 401 (correct credentials-required). The installer's rendered compose now pins nextcloud.$DOMAIN to EXTERNALIP via extra_hosts on the APP service — the exact house pattern the web service already uses for authelia. DNS inside the app container resolves the public address, the dial goes through traefik like any external client, and netguard stays fully strict (no guard relaxation, no trusted-host change). update.sh re-renders compose from the shipped lib, so running cores pick this up on upgrade. 2. Wrong endpoint: Nextcloud's DAV roots are per-user (/remote.php/dav/files/<username>/, /calendars/<username>/), but the WebDAV and CalDAV suggestion prefills handed over the bare /files/ and /calendars/ homes — one level above any valid endpoint. Both now compose the viewer's username into the URL (the URL shown is the URL saved), matching the CardDAV prefill. Dry-rendered the updated compose template and validated it with docker compose config. Regressions updated to assert the composed per-user URLs are what gets POSTed (20/20 PASS incl. the mobile suite); real-stack e2e all PASS; lint/SSR-lint/build clean. API.md and the local AGENTS invariant document the pin and the composition.
301 lines
16 KiB
TypeScript
301 lines
16 KiB
TypeScript
'use client'
|
|
|
|
// Settings → CalDAV: connect external CalDAV calendars (any RFC 4791
|
|
// service). Each server calendar materializes as its own Collection whose
|
|
// members are bookmarks — one per in-window event, carrying the event's DAV
|
|
// .ics URL — refreshed by the background engine and on demand via Sync.
|
|
// House disciplines, identical to WebDAV/MCP/notifications: 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 to prefill.
|
|
|
|
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, CalendarDays, Cloud, FlaskConical, Loader2, Plus, RefreshCw, Trash2 } from 'lucide-react'
|
|
import { toast } from 'sonner'
|
|
import { SafeDate } from '@/components/safe-format'
|
|
|
|
const KEY_MASK = '••••••••'
|
|
|
|
type CalendarRef = { href: string; name: string; collectionId: string | null }
|
|
type CalDavConnection = {
|
|
id: string; name: string; url: string; username: string
|
|
secret: string; enabled: boolean; calendars: CalendarRef[]
|
|
lastSyncedAt: string | null; lastError: string | null; version: number
|
|
}
|
|
type Suggestion = { kind: string; name: string; url: string }
|
|
type TestResult = { ok: boolean; calendars?: string[]; error?: string }
|
|
type SyncResult = { ok: boolean; calendars?: number; events?: 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 CalDavSettings() {
|
|
const { data: session } = useSession()
|
|
const [connections, setConnections] = useState<CalDavConnection[]>([])
|
|
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/caldav/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 CalDAV 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] : ''
|
|
// Nextcloud's DAV roots are per-user (/files/<username>/,
|
|
// /calendars/<username>/): compose the username into the URL so the
|
|
// prefill is a working endpoint, not a 404 one level up. The URL shown
|
|
// is the URL saved; the person can still edit both fields.
|
|
setForm({ ...emptyForm, name: s.name, username, url: username ? s.url + username + '/' : s.url })
|
|
}
|
|
const openEdit = (c: CalDavConnection) => 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/caldav/connections/${form.id}`, { method: 'PATCH', body: JSON.stringify({ ...body, version: form.version }) })
|
|
: await api('/api/caldav/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' : 'Calendar 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: CalDavConnection) => {
|
|
setTesting(c.id)
|
|
try {
|
|
const res = await api(`/api/caldav/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.calendars?.length ?? 0} calendar${data.calendars?.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: CalDavConnection) => {
|
|
setSyncing(c.id)
|
|
try {
|
|
const res = await api(`/api/caldav/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.events} event${data.events === 1 ? '' : 's'} from ${data.calendars} calendar${data.calendars === 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: CalDavConnection) => {
|
|
const res = await api(`/api/caldav/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: CalDavConnection) => {
|
|
const res = await api(`/api/caldav/connections/${c.id}`, { method: 'DELETE' })
|
|
if (res.ok) { toast.success(`Removed ${c.name} — the calendar 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 CalDAV 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"><CalendarDays className="h-4 w-4" /> CalDAV calendars</h3>
|
|
<p className="text-sm text-muted-foreground mt-1">
|
|
Connect a calendar from any CalDAV service. Each calendar becomes a Collection, one
|
|
bookmark per upcoming event, re-checked in the background every 30 minutes. Passwords
|
|
are encrypted at rest and never shown again.
|
|
</p>
|
|
</div>
|
|
{allowed && <Button size="sm" onClick={openCreate}><Plus className="h-4 w-4 mr-1" /> Connect calendar</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>CalDAV calendars 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 CalDAV calendars 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>
|
|
{c.calendars?.length > 0 && <Badge variant="outline" className="shrink-0 text-[10px]">{c.calendars.length} calendars</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.calendars) && c.calendars.length > 0 && (
|
|
<p className="text-xs text-muted-foreground">
|
|
Calendars: {c.calendars.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.events} events across {r.sync.calendars ?? 0} calendars: {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.calendars?.join(', ') || 'no calendars'}
|
|
</p>
|
|
)}
|
|
</li>
|
|
)
|
|
})}
|
|
</ul>
|
|
)}
|
|
|
|
<Dialog open={form !== null} onOpenChange={(open) => { if (!open) setForm(null) }}>
|
|
<DialogContent className="max-w-lg">
|
|
<DialogHeader><DialogTitle>{form?.id ? 'Edit CalDAV connection' : 'Connect a CalDAV calendar'}</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 calendar" maxLength={100} />
|
|
</div>
|
|
<div>
|
|
<label className="text-xs font-medium">Calendar URL</label>
|
|
<Input value={form.url} onChange={e => setForm({ ...form, url: e.target.value })} placeholder="https://cloud.example.com/remote.php/dav/calendars/username" />
|
|
<p className="mt-1 text-xs text-muted-foreground">A calendar home or a single calendar on a public http(s) endpoint — dials are network-guarded and never follow 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 calendar'}</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</DialogContent>
|
|
</Dialog>
|
|
</div>
|
|
)
|
|
}
|