import { html, useState, useEffect, useCallback, useMemo, useRef, } from './vendor/htm-preact.js'; import { t } from './i18n.js'; import { ask } from './ask.js'; import { Icon } from './icon.js'; import { CollapsibleSection, ToggleSwitch } from './settings-ui.js'; import { hubFetch, navigate } from './hub-client.js'; import { availableApps, configurableApps } from './apps.js'; import * as platform from './platform.js'; import { inviteLinkHere, nodePkForLink } from './invite-link.js'; // The account preference behind the "send by e-mail" box. The hub's // ALLOWED_PREF_KEYS must list it, or every toggle snaps back. export const INVITE_EMAIL_PREF = 'invite_email'; // How many times the settings page asks the node on this machine before it // decides there is none. One ask is a 3 s `node:detect`, and a node busy // indexing a large root can miss it: a single miss used to hide "Add a // directory" until the page was reloaded. Found live, by a tester adding a // sixth directory while the others were still indexing. const NODE_CHECK_ATTEMPTS = 4; const NODE_CHECK_DELAY_MS = 2000; /** * What the node on this machine says about `groupId`: `{ group }`, with * `group` null when that node does not host it, or null when no node answers. * A miss is asked again; a machine with no node set up at all is not. */ async function readLocalNode(node, groupId, attempts = NODE_CHECK_ATTEMPTS, delayMs = NODE_CHECK_DELAY_MS) { for (let i = 0; i < attempts; i++) { if (i) await new Promise(r => setTimeout(r, delayMs)); try { const detect = await node.detect(); if (!detect.detected) { if (!detect.configured) return null; continue; } const data = await node.op('groups'); return { group: (data.groups || []).find(g => g.id === groupId) || null }; } catch { /* busy, or mid-reload: ask again */ } } return null; } // ── Shared Directories Table ──────────────────────────────────────────── // How often the table asks its node what it could not read. const TROUBLE_POLL_MS = 10000; /** * A group's root directories, and the operator's controls over them. * * One component, two modes, because the Create Group wizard and the Settings * page were drifting apart while showing the same thing: * * mode="live" — a hosted group. What widens the node's sharing — adding * a directory, its `writable` and `removable` switches — goes * through the loopback API only, so only on the node's own * machine. Removing, ejecting, plugging, pausing and * resuming are signed ops over MNP, or the loopback API when * there is no connection. * mode="local" — the wizard, before the group exists. Changes are held in * an array the caller owns; nothing is persisted until the * group is attached. * * **The list is shown wherever the operator is.** They may be signing in from * any browser, and the only thing that reaches their node from there is MNP. * An earlier version of this read its roots exclusively from the loopback API, * which resolves to "not available" in a browser — so the section rendered for * nobody on the web. `mnpRoots` is the source whenever a connection exists; the * loopback list is the fallback for a local node that is not currently * connected (a group still scanning, say). From a browser the table is read * only where it would widen anything (MNP 6.0). * * Props: * roots — the node's current roots: { name, path, writable, * removable, ejected, paused, available, kind } * groupId — the group id * transport — MeshBayTransport instance, or null when not connected * signFn — signing function for admin ops * nodeDetected — whether the loopback node API answers * onRootsChange — called after a change, to re-read the loopback list * onRefreshIndex — full index refresh. Not called after a root change: see * `run()` for why the node's own push is what settles it * mode — "live" (default) or "local" * localRoots / onLocalRootsChange — the array, in "local" mode */ function SharedDirectoriesTable({ roots, groupId, transport, signFn, nodeDetected: nodeAvail, onRootsChange, onRefreshIndex, mode = 'live', localRoots, onLocalRootsChange }) { const isLocal = mode === 'local'; const serverRoots = isLocal ? (localRoots || []) : (roots || []); const [busy, setBusy] = useState(false); // `{ text, error }` — a refusal has to look like one. Every message here was // a `settings-hint`, which is dim grey body text, so "two roots would both // be called uploads" read as a footnote to the section rather than as the // reason nothing happened. const [msg, setMsg] = useState(null); const [indexProgress, setIndexProgress] = useState(null); // What the node could not read and the folders it paused by itself, as its // loopback API says them; `troubleTick` asks again after a change here. const [trouble, setTrouble] = useState(null); const [troubleTick, setTroubleTick] = useState(0); const say = useCallback((text) => setMsg(text ? { text, error: false } : null), []); const refuse = useCallback((text) => setMsg({ text, error: true }), []); // Rendered at the foot of the section, under the Add button — the last thing // below the control that caused it, rather than above a table the eye has // already moved past. const message = !msg ? '' : html`
${msg.text}
`; // A toggle has to move under the finger, and the answer only comes back // when the node has signed, written node.toml and pushed the new table. // The patch is therefore held until the incoming `roots` actually agrees // with it — clearing it when the request resolves (which is what this did) // drops it in the frame *before* the new table arrives, so the switch // visibly snaps back and then forward again. const [optimistic, setOptimistic] = useState({}); useEffect(() => { setOptimistic((prev) => { const keys = Object.keys(prev); if (!keys.length) return prev; const next = {}; let changed = false; for (const name of keys) { const server = serverRoots.find(r => r.name === name); const patch = prev[name]; // Gone from the table, or the server now says what we asked for: // either way this patch has nothing left to hide. const settled = !server || Object.keys(patch).every(k => server[k] === patch[k]); if (settled) changed = true; else next[name] = patch; } return changed ? next : prev; }); }, [serverRoots]); const displayRoots = serverRoots.map(r => optimistic[r.name] ? { ...r, ...optimistic[r.name] } : r); // Paths are the operator's own view and do not cross MNP: the roots table // rides in the index payload, which every member receives, and it tells them // what exists and whether it is readable — never where on the operator's // disk it lives. So the column appears when the answer is actually // available (the loopback API, which is already this machine only) and is // left out otherwise, rather than printing a row of blanks. const hasPaths = displayRoots.some((r) => r.path); // Which door a change goes through. // // Widening what the node shares — a new directory, `writable`, `removable` — // only through the loopback API, which exists only on the node's own // machine. Over MNP these were signed ops, and a // signature proves that the operator's key signed, not that the operator // meant it: in a browser that key is driven by code the hub serves. // // Narrowing — remove, eject, plug, pause, resume — MNP first, then loopback. const overMnp = !isLocal && transport && transport.connected; const overLoopback = !isLocal && !overMnp && nodeAvail; const onNodeMachine = !isLocal && nodeAvail; const canEdit = isLocal || overMnp || overLoopback; const canWiden = isLocal || onNodeMachine; // Paths, so only where the loopback API answers: on the node's own machine. // An operator elsewhere sees the folder paused, as any member does. useEffect(() => { if (!onNodeMachine) { setTrouble(null); return undefined; } let stopped = false; const read = async () => { try { const s = await platform.node.op('groupIndexStatus', { groupId }); const next = { unread: s.unread || [], total: s.unread_total || 0, stalled: s.stalled || [] }; if (!stopped) { setTrouble((prev) => JSON.stringify(prev) === JSON.stringify(next) ? prev : next); } } catch { /* busy, or mid-reload: the next poll asks again */ } }; read(); const id = setInterval(read, TROUBLE_POLL_MS); return () => { stopped = true; clearInterval(id); }; }, [onNodeMachine, groupId, troubleTick]); // Deliberately no index refresh after a root change. // // Adding a root makes the node reload, which rescans — minutes on a real // library — and the reload is fire-and-forget for that reason. Fetching the // index in the moment after therefore returns the set from *before* it, and // `applyIndex` writes that over the roots the ack had just delivered: the // new directory appeared for one paint and vanished, which is what "it only // shows up after a refresh" was. // // Nothing is lost by waiting. The ack carries the new table immediately, and // the delta the node pushes when the scan finishes carries it again along // with the files. const run = useCallback(async (work) => { setBusy(true); setMsg(null); try { await work(); if (onRootsChange) await onRootsChange(); return true; } catch (err) { refuse(platform.bridgeMessage(err)); return false; } finally { setBusy(false); setTroubleTick((n) => n + 1); } }, [onRootsChange, refuse]); const doUpdateRoot = useCallback(async (rootName, updates) => { if (isLocal) { if (onLocalRootsChange) { onLocalRootsChange((localRoots || []).map(r => r.name === rootName ? { ...r, ...updates } : r)); } return; } setOptimistic(prev => ({ ...prev, [rootName]: { ...(prev[rootName] || {}), ...updates }, })); const ok = await run(async () => { if (onNodeMachine) await platform.node.op('updateRoot', { groupId, rootName, updates }); else throw new Error(t('settings_node.roots_local_only_hint')); }); // Only a failure clears the patch here; a success waits for the node's // own table, so the switch never travels backwards on its way forwards. if (!ok) { setOptimistic(prev => { const next = { ...prev }; delete next[rootName]; return next; }); } }, [isLocal, localRoots, onLocalRootsChange, onNodeMachine, groupId, run]); const doEjectRoot = useCallback((rootName) => run(async () => { if (overMnp) await transport.ejectRoot(groupId, rootName, signFn); else if (overLoopback) await platform.node.op('ejectRoot', { groupId, rootName }); else throw new Error(t('node.root_no_route')); }), [overMnp, overLoopback, transport, groupId, signFn, run]); const doPlugRoot = useCallback((rootName) => run(async () => { if (overMnp) await transport.plugRoot(groupId, rootName, signFn); else if (overLoopback) await platform.node.op('plugRoot', { groupId, rootName }); else throw new Error(t('node.root_no_route')); }), [overMnp, overLoopback, transport, groupId, signFn, run]); const doPauseRoot = useCallback((rootName) => run(async () => { if (overMnp) await transport.pauseRoot(groupId, rootName, signFn); else if (overLoopback) await platform.node.op('pauseRoot', { groupId, rootName }); else throw new Error(t('node.root_no_route')); }), [overMnp, overLoopback, transport, groupId, signFn, run]); const doResumeRoot = useCallback((rootName) => run(async () => { if (overMnp) await transport.resumeRoot(groupId, rootName, signFn); else if (overLoopback) await platform.node.op('resumeRoot', { groupId, rootName }); else throw new Error(t('node.root_no_route')); }), [overMnp, overLoopback, transport, groupId, signFn, run]); const doRemoveRoot = useCallback(async (rootName) => { if (isLocal) { if (onLocalRootsChange) { onLocalRootsChange((localRoots || []).filter(r => r.name !== rootName)); } return; } if (!await ask(t('node.root_remove_confirm', { name: rootName }))) return; const ok = await run(async () => { if (overMnp) await transport.removeRoot(groupId, rootName, signFn); else if (overLoopback) { await platform.node.op('removeRoot', { groupId, rootName }); await platform.node.op('reload'); } else throw new Error(t('node.root_no_route')); }); if (ok) say(t('node.root_removed')); }, [isLocal, localRoots, onLocalRootsChange, overMnp, overLoopback, transport, groupId, signFn, run]); // Adding a root: a native folder picker on the node's own machine, and // nothing anywhere else — a path typed into a page is a path a script in the // page could have typed. const addRootAtPath = useCallback(async (path, name) => { if (isLocal) { if ((localRoots || []).some(r => r.path === path)) return true; const isFirst = (localRoots || []).length === 0; // The first directory is writable so a new group can receive an upload // without the operator having to find this switch first. Every later // one is read-only until they say otherwise. if (onLocalRootsChange) { onLocalRootsChange([...(localRoots || []), { name, path, writable: isFirst, removable: false }]); } return true; } setIndexProgress(null); return run(async () => { if (!onNodeMachine) throw new Error(t('settings_node.roots_local_only_hint')); await platform.node.op('addRoot', { groupId, path, name }); await platform.node.op('reload'); await platform.watchIndexProgress(groupId, setIndexProgress); }); }, [isLocal, localRoots, onLocalRootsChange, onNodeMachine, groupId, run]); const doPickRoot = useCallback(async () => { const chosen = await platform.rootPicker.choose(); if (!chosen) return; const ok = await addRootAtPath(chosen.path, chosen.name); if (ok && !isLocal) say(t('node.root_added')); }, [addRootAtPath, isLocal]); const addControls = !canWiden || !platform.rootPicker.available ? '' : html` `; // Said once, under the table, rather than as a tooltip on each switch: the // switches are not broken, they are somewhere else. const localOnlyHint = canEdit && !canWiden && html`${t('settings_node.roots_local_only_hint')}
`; // A folder the node paused because its disk stopped answering, and the // files it gave up on. Under the table, with the paths: this is the list an // operator used to need the node's log for. const stalledAt = {}; for (const s of (trouble && trouble.stalled) || []) { if (displayRoots.some((r) => r.name === s.root && r.paused)) stalledAt[s.root] = s.path; } const troubleNote = (isLocal || !trouble) ? '' : html` ${Object.entries(stalledAt).map(([name, file]) => html`${t('node.root_stalled_hint', { name, file })}
`)} ${trouble.total > 0 && html`${t('node.unread_more', { count: trouble.total - trouble.unread.length })}
`}${t('group.offline_title')}
` : !operatorPaired ? html`${isNodeAdmin ? t('members.invite_needs_pairing') : t('members.invite_ask_operator')}
` : ''}${t('members.link_hint')}
${linkError && html`${t('members.pair_hint')}
${pairStatus && html`${pairStatus === 'paired' ? t('members.pair_success') : pairStatus}
`}${t('settings_node.shared_directories_hint')}
${!connected && nodeDetected && html`${t('settings_node.roots_offline_hint')}
`} <${SharedDirectoriesTable} roots=${effectiveRoots} groupId=${groupId} transport=${transportRef.current} signFn=${adminSignFn} nodeDetected=${nodeDetected && nodeHostsGroup} onRootsChange=${loadNodeInfo} onRefreshIndex=${onRefreshIndex} /> ${CollapsibleSection}> `} ${/* One collapsible section per application, from the registry. Adding an app adds an entry to `apps.js` and a settings file; this loop names none of them. The toggle in the header *is* the enablement control — a separate checkbox list somewhere else meant the operator turned an app on in one place and configured it in another, with the two able to disagree. Collapsed by default, and the settings inside are not rendered at all while the app is off: a form for something that is not running is a form whose Save button does nothing anyone can see. */ isNodeAdmin && connected && configurableApps().map((app) => html` <${CollapsibleSection} key=${app.key} defaultOpen=${false} title=${html` `} action=${html` <${ToggleSwitch} checked=${activeApps.includes(app.key)} disabled=${appsBusy} onChange=${() => toggleApp(app.key)} /> `}> ${activeApps.includes(app.key) ? html`<${app.Settings} roots=${effectiveRoots} dirs=${folderOptions} settings=${appSettings} saveDirectories=${(paths) => saveAppDirectories(app.key, paths)} transport=${transportRef.current} signFn=${adminSignFn} />` : html`${t('settings_app.disabled_hint')}
`} ${CollapsibleSection}> `)} ${appsMsg && html`${appsMsg}
`} ${/* Whether this group shows up in members' cross-group Search. A listing preference, not a permission: the hint says so, because a switch next to "members" and "devices" reads as access control. */ isNodeAdmin && connected && html` <${CollapsibleSection} titleKey="settings_node.search_listed_title" defaultOpen=${false}>${t('settings_node.search_listed_hint')}
${listedMsg && html`${listedMsg}
`} ${CollapsibleSection}> `} ${/* How hard the node works watching its own disk — indexer.py DirectoryIndexer. A performance knob, not a permission: it changes nothing about who can see or do what. */ isNodeAdmin && connected && html` <${CollapsibleSection} titleKey="settings_node.scan_title" defaultOpen=${false}>${t('settings_node.scan_hint')}
${scanMsg}
`} ${CollapsibleSection}> `} ${/* Delete/leave — node detach first (reversible), then hub delete (irreversible). Closed by default: a danger-zone action is one click away either way, but not the first thing seen on open. */ html` <${CollapsibleSection} defaultOpen=${false} title=${isOwner ? t('group.delete_group') : t('group.leave')}>${t('device.mine_hint')}
${deviceMsg && html`${deviceMsg}
`} ${devices.length === 0 ? html`${t('device.mine_empty')}
` : html`| ${t('admin.col_username')} | ${t('members.group_role')} | |
|---|---|---|
| ${m.username} | ${m.user_id === adminId ? html`${t('members.owner')}` : html`${t('members.member')}` } | ${isAdmin && m.user_id !== adminId && html` `} |
| ${m.username} | ${t('members.awaiting_code')} | |
| ${m.username} | ${t('members.invited')} | ${isAdmin && html` `} |
${t('members.remove_hint')}
`} ${CollapsibleSection}> ${ownsGroup && html` <${CollapsibleSection} title=${t('hosts.title')}>${t('hosts.hint')}
${hosts.length === 0 && html`${t('hosts.none')}
`} ${hosts.length > 0 && html`${t('hosts.from', { name: h.username })}
${h.pk_node} |
${t(`hosts.status_${h.status}`)} ${h.online && html` ${t('hosts.online')}`} | ${h.status !== 'approved' && html` `} ${h.status !== 'refused' && html` `} |