'use client' // Settings → WebDAV: connect external WebDAV file shares (any RFC 4918 // service). A connected share materializes as a Collection whose members // are bookmarks — one per file, carrying the file's DAV URL — refreshed by // the background engine and on demand via Sync. House disciplines, identical // to 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, Cloud, FlaskConical, FolderSync, Loader2, Plus, RefreshCw, Trash2 } from 'lucide-react' import { toast } from 'sonner' import { SafeDate } from '@/components/safe-format' const KEY_MASK = '••••••••' type WebdavConnection = { id: string; name: string; url: string; username: string secret: string; collectionId: string | null; enabled: boolean lastSyncedAt: string | null; lastError: string | null; version: number } type Suggestion = { kind: string; name: string; url: string } type TestResult = { ok: boolean; error?: string } type SyncResult = { ok: boolean; files?: 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 { return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init }) } export function WebdavSettings() { const { data: session } = useSession() const [connections, setConnections] = useState([]) const [suggestions, setSuggestions] = useState([]) const [allowed, setAllowed] = useState(true) const [loading, setLoading] = useState(true) const [form, setForm] = useState(null) const [saving, setSaving] = useState(false) const [testing, setTesting] = useState(null) const [syncing, setSyncing] = useState(null) const [results, setResults] = useState>({}) const reload = useCallback(() => api('/api/webdav/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 WebDAV 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//, // /calendars//): 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: WebdavConnection) => 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 = { 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/webdav/connections/${form.id}`, { method: 'PATCH', body: JSON.stringify({ ...body, version: form.version }) }) : await api('/api/webdav/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' : 'Share connected — sync it to materialize the collection') setForm(null) await reload() } catch { toast.error('Could not save the connection') } finally { setSaving(false) } } const test = async (c: WebdavConnection) => { setTesting(c.id) try { const res = await api(`/api/webdav/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('The share answered') } catch { setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], test: { ok: false, error: 'Network error' } } })) } finally { setTesting(null) } } const sync = async (c: WebdavConnection) => { setSyncing(c.id) try { const res = await api(`/api/webdav/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.files} file${data.files === 1 ? '' : 's'}${data.created ? ` (${data.created} new)` : data.removed ? ` (${data.removed} detached)` : ''}`) await reload() } catch { setResults(prev => ({ ...prev, [c.id]: { ...prev[c.id], sync: { ok: false, error: 'Network error' } } })) } finally { setSyncing(null) } } const toggle = async (c: WebdavConnection) => { const res = await api(`/api/webdav/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: WebdavConnection) => { const res = await api(`/api/webdav/connections/${c.id}`, { method: 'DELETE' }) if (res.ok) { toast.success(`Removed ${c.name} — the collection and its bookmarks stay`); await reload() } else toast.error((await res.json().catch(() => null))?.error ?? 'Could not remove') } if (loading) { return (
Loading WebDAV shares…
) } return (

WebDAV file shares

Connect a share from any WebDAV service. It becomes a Collection, one bookmark per file, re-checked in the background every 30 minutes. Passwords are encrypted at rest and never shown again.

{allowed && }
{!allowed && (

WebDAV shares are not available on your current plan. Existing shares stay connected but no longer sync.

)} {suggestions.length > 0 && allowed && (
{suggestions.map(s => (

{s.name} detected on this server

{s.url}

))}
)} {connections.length === 0 ? (

No WebDAV shares connected.

) : (
    {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 (
  • toggle(c)} aria-label={`Enable ${c.name}`} /> {c.name} {c.collectionId && collection}

    {c.username}@{c.url}

    {c.lastSyncedAt ? <>Last synced : 'Not synced yet — use Sync to materialize the collection'}

    {!failure && c.lastError && (

    {c.lastError}

    )} {failure &&

    {failure}

    } {r?.sync?.ok && (

    {r.sync.files} files: {r.sync.created ?? 0} created, {r.sync.reused ?? 0} reused,{" "} {r.sync.updated ?? 0} changed, {r.sync.removed ?? 0} detached {r.sync.truncated && ' — listing was capped; nothing was treated as deleted'}

    )} {r?.test?.ok &&

    PROPFIND answered — the share and credentials work.

    }
  • ) })}
)} { if (!open) setForm(null) }}> {form?.id ? 'Edit WebDAV connection' : 'Connect a WebDAV share'} {form && (
setForm({ ...form, name: e.target.value })} placeholder="e.g. House documents" maxLength={100} />

Also names the Collection the share materializes into.

setForm({ ...form, url: e.target.value })} placeholder="https://cloud.example.com/remote.php/dav/files/username/Documents" />

Any WebDAV folder on a public http(s) endpoint — dials are network-guarded and never follow redirects.

setForm({ ...form, username: e.target.value })} placeholder="erwin" maxLength={200} />
setForm({ ...form, password: e.target.value })} placeholder={form.hasStoredSecret ? `${KEY_MASK} (leave blank to keep)` : 'Account or app password'} maxLength={2000} />
{form.hasStoredSecret &&

Stored credentials are never shown; blank keeps the current one.

}

Tip: services that use two-factor login usually need an app password here (in Nextcloud: Settings → Security → Devices).

)}
) }