Files
linux-cloud-router/web/src/SitesPanel.tsx
T

285 lines
12 KiB
TypeScript

import Add from '@mui/icons-material/Add'
import Block from '@mui/icons-material/Block'
import CheckCircle from '@mui/icons-material/CheckCircle'
import Delete from '@mui/icons-material/Delete'
import Edit from '@mui/icons-material/Edit'
import FolderOpen from '@mui/icons-material/FolderOpen'
import Refresh from '@mui/icons-material/Refresh'
import Settings from '@mui/icons-material/Settings'
import { Alert, Box, Button, Checkbox, Chip, FormControlLabel, IconButton, Link, Stack, Table, TableBody, TableCell, TableHead, TableRow, Tooltip } from '@mui/material'
import { useCallback, useEffect, useState, type ReactNode } from 'react'
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import { Copyable, Pairs } from './ServerPanel.tsx'
import SearchField from './SearchField.tsx'
import { matches } from './search.ts'
import SiteDialog, { type SiteSettings } from './SiteDialog.tsx'
import SitesSettingsDialog from './SitesSettingsDialog.tsx'
import Toolbar from './Toolbar.tsx'
import {
ApiError, DETAILS_SHAPE, GROUPS_SHAPE, REMOVED_SHAPE, SITES_SETTINGS_SHAPE, SITES_SHAPE, SITE_DNS_ADDRESS_LABELS,
SITE_DNS_LABELS, SITE_SHAPE, SITE_TLS_LABELS, request, type Group, type RouterDetails, type Site, type Sites,
} from './api.ts'
/** The localStorage key of the tab's layout. */
const LAYOUT_KEY = 'linux-manager-ui.sites-layout'
/** The URLs of a site: its scheme, each host name and its port when it is not the scheme's default. */
function siteUrls(site: Site) {
const scheme = site.tls === 'none' ? 'http' : 'https'
const port = site.port === (site.tls === 'none' ? 80 : 443) ? '' : `:${site.port}`
return site.hosts.filter((host) => !host.startsWith('*.')).map((host) => `${scheme}://${host.includes(':') ? `[${host}]` : host}${port}`)
}
/**
* The web sites of the server's /sites, which Caddy serves from folders on the server. The Settings panel shows the
* sites section, whether they are served, the largest upload and WebDAV with its URL, edited with Settings. The list
* shows each site with its URLs, port, interfaces, TLS, editors group, DNS and state: add, edit, enable, disable,
* remove, with its folder when asked, and open its files on the Files tab with onOpenFiles. The panels are on a
* PanelBoard whose layout is kept in the browser.
*/
export default function SitesPanel(props: { onOpenFiles: (name: string) => void }) {
const [sites, setSites] = useState<Sites | null>(null)
const [fqdn, setFqdn] = useState('')
const [cas, setCas] = useState<string[]>([])
const [groups, setGroups] = useState<string[]>([])
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [busy, setBusy] = useState(true)
const [adding, setAdding] = useState(false)
const [editing, setEditing] = useState<Site | null>(null)
const [settings, setSettings] = useState(false)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const [search, setSearch] = useState('')
const board = useBoard(LAYOUT_KEY)
/** Reads the sites with the groups and the server's details; the state changes only once the server answers. */
const read = useCallback(async () => {
await Promise.all([
request<Sites>('GET', '/sites', SITES_SHAPE),
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
request<RouterDetails>('GET', '/config', DETAILS_SHAPE),
])
.then(([found, groupList, details]) => {
setSites(found)
setGroups(groupList.groups.map((group) => group.name))
const wan = details.configuration.wan ?? {}
const pki = details.configuration.pki ?? {}
setFqdn(typeof wan.local_fqdn === 'string' ? wan.local_fqdn : '')
setCas(typeof pki.issuing_cas === 'object' && pki.issuing_cas !== null ? Object.keys(pki.issuing_cas) : [])
setError(null)
setUnavailable(false)
}, (caught) => {
const failure = caught as ApiError
setSites(null)
setUnavailable(failure.status === 404)
setError(failure.message)
})
.finally(() => setBusy(false))
}, [])
/** Reads the sites again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void read()
}, [read])
/** Runs a change of a site, then reads the list again; a failure is shown above the list. */
async function change(work: () => Promise<unknown>) {
setBusy(true)
let failure: string | null = null
try {
await work()
} catch (caught) {
failure = (caught as Error).message
}
await refresh()
if (failure !== null) {
setError(failure)
}
}
function remove(site: Site) {
let content = false
setConfirm({
title: 'Remove site',
message: `Remove ${site.name}?`,
confirmLabel: 'Remove',
destructive: true,
children: (
<FormControlLabel
control={<Checkbox onChange={(event) => { content = event.target.checked }} />}
label={`Remove its folder ${site.directory}`}
/>
),
onCancel: () => setConfirm(null),
onConfirm: () => {
setConfirm(null)
void change(() => request('DELETE', `/sites/${site.name}${content ? '?content=true' : ''}`, REMOVED_SHAPE))
},
})
}
const section = sites?.settings
const shown = (sites?.sites ?? []).filter((site) => matches(search, [site.name, ...site.hosts, site.editors]))
const panels: BoardPanel[] = [
...(section ? [{
id: 'settings',
title: 'Settings',
wide: true,
content: (
<Pairs
rows={[
['State', <Chip key="state" size="small" label={section.enabled ? 'served' : 'not served'} color={section.enabled ? 'success' : 'default'} />],
['Largest upload', `${section.upload_max_mb} MiB`],
['WebDAV', <Chip key="webdav" size="small" label={section.webdav ? 'enabled' : 'disabled'} color={section.webdav ? 'success' : 'default'} />],
...(section.webdav && fqdn
? [['WebDAV URL', <Copyable key="url" value={`https://${fqdn}:${section.webdav_port}/`} label="WebDAV URL" />]] as [string, ReactNode][]
: []),
]}
/>
),
}] : []),
...(sites ? [{
id: 'sites',
title: 'Sites',
wide: true,
content: (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>URLs</TableCell>
<TableCell>Port</TableCell>
<TableCell>Listen</TableCell>
<TableCell>TLS</TableCell>
<TableCell>Editors</TableCell>
<TableCell>DNS</TableCell>
<TableCell>State</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{shown.length === 0 && (
<TableRow>
<TableCell colSpan={9} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{shown.map((site) => (
<TableRow key={site.name} hover>
<TableCell>{site.name}</TableCell>
<TableCell>
<Stack>
{siteUrls(site).map((url) => <Link key={url} href={url} target="_blank" rel="noreferrer">{url}</Link>)}
{site.hosts.length === 0 && 'any host name'}
</Stack>
</TableCell>
<TableCell>{site.port}</TableCell>
<TableCell>{site.listen}</TableCell>
<TableCell>{SITE_TLS_LABELS[site.tls]}{site.tls === 'ca' ? ` (${site.ca})` : ''}</TableCell>
<TableCell>{site.editors || '-'}</TableCell>
<TableCell>{SITE_DNS_LABELS[site.dns]}{site.dns === 'router' ? `, ${SITE_DNS_ADDRESS_LABELS[site.dns_address]}` : ''}</TableCell>
<TableCell sx={{ color: site.enabled ? 'success.main' : 'text.secondary' }}>{site.enabled ? 'enabled' : 'disabled'}</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
<Tooltip title="Files">
<span>
<IconButton size="small" onClick={() => props.onOpenFiles(site.name)}><FolderOpen fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setEditing(site)}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title={site.enabled ? 'Disable' : 'Enable'}>
<span>
<IconButton
size="small"
disabled={busy}
onClick={() => void change(() => request('PUT', `/sites/${site.name}`, SITE_SHAPE, { enabled: !site.enabled }))}
>
{site.enabled ? <Block fontSize="small" /> : <CheckCircle fontSize="small" />}
</IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => remove(site)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
),
}] : []),
]
return (
<Box component="section">
<Toolbar description="Static web sites Caddy serves from folders on the server.">
<SearchField value={search} onChange={setSearch} />
<Button variant="outlined" startIcon={<Settings />} disabled={busy || !section} onClick={() => setSettings(true)}>
Settings
</Button>
<Button variant="contained" startIcon={<Add />} disabled={busy || sites === null} onClick={() => setAdding(true)}>
Add
</Button>
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>
Refresh
</Button>
</Toolbar>
{error && <Alert severity={unavailable ? 'info' : 'error'} sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
<Board board={board} panels={panels} />
{adding && (
<SiteDialog
cas={cas}
groups={groups}
onCancel={() => setAdding(false)}
onSave={async (name, values: SiteSettings) => {
await request('POST', '/sites', SITE_SHAPE, { name, ...values })
setAdding(false)
await refresh()
}}
/>
)}
{editing && (
<SiteDialog
site={editing}
cas={cas}
groups={groups}
onCancel={() => setEditing(null)}
onSave={async (name, values: SiteSettings) => {
await request('PUT', `/sites/${name}`, SITE_SHAPE, values)
setEditing(null)
await refresh()
}}
/>
)}
{settings && section && (
<SitesSettingsDialog
current={section}
onCancel={() => setSettings(false)}
onSave={async (values) => {
await request('PUT', '/sites', SITES_SETTINGS_SHAPE, values)
setSettings(false)
await refresh()
}}
/>
)}
{confirm && <ConfirmDialog {...confirm} />}
</Box>
)
}