feat(core): persist viewer state and integrate Cesium services and profiles
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
|
||||
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
|
||||
import { CesiumServiceSettings } from "./map/CesiumServiceSettings";
|
||||
import { useLabStorageSettings } from "./storage/LabStorageSettings";
|
||||
import { roots, workspaces, workspacesForRoot } from "../productModel";
|
||||
|
||||
@@ -18,7 +19,7 @@ const surfaces = environmentSurfaceIds.map(id => ({
|
||||
}));
|
||||
export function EnvironmentSettingsWindow(props: Props) {
|
||||
const storage = useLabStorageSettings(props.open);
|
||||
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage]}
|
||||
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage, {id: "services", label: "Сервисы", icon: "key", content: props.open ? <CesiumServiceSettings/> : null}]}
|
||||
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
|
||||
onUpload={(id, itemId, file) => {
|
||||
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import {useEffect, useState} from "react";
|
||||
import {Description, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField} from "@nodedc/ui-react";
|
||||
import {cesiumServiceMessage, cesiumTokenIndicator, readCesiumService, saveCesiumService, verifyCesiumService,
|
||||
type CesiumRouteMode, type CesiumServiceSettings as Settings, type CesiumVerification} from "../../core/map/cesiumService";
|
||||
import "./cesiumServiceSettings.css";
|
||||
import {serverRequest, type Server} from "../../core/system/servers";
|
||||
|
||||
export function CesiumServiceSettings() {
|
||||
const [service, setService] = useState("");
|
||||
const [pending, setPending] = useState<"verify" | "save" | "remove" | null>(null);
|
||||
const [settings, setSettings] = useState<Settings | null>(null);
|
||||
const [mode, setMode] = useState<CesiumRouteMode>("auto");
|
||||
const [egress, setEgress] = useState("");
|
||||
const [servers, setServers] = useState<Server[]>([]);
|
||||
const [routesError, setRoutesError] = useState("");
|
||||
const [token, setToken] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [checkError, setCheckError] = useState("");
|
||||
const [showVerification, setShowVerification] = useState(false);
|
||||
const [verification, setVerification] = useState<CesiumVerification | null>(null);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void readCesiumService().then(value => {if (active) {setSettings(value); setMode(value.mode); setEgress(value.egress_id || "");}})
|
||||
.catch(reason => {if (active) setError(reason.message);});
|
||||
void serverRequest<{items:Server[]}>("").then(value => {if(active) setServers(value.items);})
|
||||
.catch(reason => {if(active) setRoutesError(reason.message);});
|
||||
return () => {active = false;};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setVerification(null); setCheckError(""); setShowVerification(false);
|
||||
if (service !== "cesium" || !settings?.token_configured || token.trim() || egress !== (settings.egress_id || "")) {setChecking(false); return;}
|
||||
setChecking(true);
|
||||
void verifyCesiumService().then(value => {if (active) setVerification(value);})
|
||||
.catch(reason => {if (active) setCheckError(reason instanceof Error ? reason.message : cesiumServiceMessage());})
|
||||
.finally(() => {if (active) setChecking(false);});
|
||||
return () => {active = false;};
|
||||
}, [service, settings?.revision, settings?.token_configured, token, egress]);
|
||||
const indicator = cesiumTokenIndicator({configured: !!settings?.token_configured, draft: !!token.trim(),
|
||||
checking: checking || pending === "verify" || pending === "save", error: error || checkError, verification});
|
||||
async function action(kind: "verify" | "save" | "remove") {
|
||||
if (!settings || busy) return;
|
||||
setBusy(true); setPending(kind); setError(""); setCheckError(""); setVerification(null); setShowVerification(kind === "verify");
|
||||
try {
|
||||
if (kind === "verify") setVerification(await verifyCesiumService(token.trim() || undefined, egress));
|
||||
else {
|
||||
const result = await saveCesiumService({revision: settings.revision, mode, egress_id: egress,
|
||||
...(kind === "remove" ? {remove_token: true} : token.trim() ? {token: token.trim()} : {})});
|
||||
setSettings(result); setToken("");
|
||||
}
|
||||
} catch (reason) {setError(reason instanceof Error ? reason.message : cesiumServiceMessage());}
|
||||
finally {setBusy(false); setPending(null);}
|
||||
}
|
||||
return <SettingsCard title="Сервисы" actions={service === "cesium" && <>
|
||||
<IconButton label="Проверить доступ" disabled={busy || checking || !settings || (!token.trim() && !settings.token_configured)}
|
||||
loading={pending === "verify"} onClick={() => void action("verify")}><Icon name="activity"/></IconButton>
|
||||
<IconButton label="Сохранить" disabled={busy || !settings} loading={pending === "save"}
|
||||
onClick={() => void action("save")}><Icon name="save"/></IconButton>
|
||||
{settings?.token_configured && <IconButton label="Удалить токен" disabled={busy} loading={pending === "remove"}
|
||||
onClick={() => void action("remove")}><Icon name="trash"/></IconButton>}
|
||||
</>}>
|
||||
<Select label="Выберите сервис" value={service} disabled={busy} onChange={setService}
|
||||
options={[{value: "", label: "Выберите сервис"}, {value: "cesium", label: "Cesium ion",
|
||||
icon: <StatusBadge variant="indicator" tone={indicator.tone} pulse={indicator.pulse} title={indicator.label} aria-label={indicator.label}/>} ]}/>
|
||||
{service === "cesium" && <>
|
||||
<Description>Общий доступ к спутниковым картам, рельефу и зданиям во всех разделах Mission Core.</Description>
|
||||
{!settings && !error && <Description role="status">Получаем настройки…</Description>}
|
||||
{settings && <>
|
||||
<Select label="Подключение" value={mode} disabled={busy} onChange={value => setMode(value as CesiumRouteMode)}
|
||||
options={[{value: "auto", label: "Автоматически"}, {value: "direct", label: "Напрямую к источнику"},
|
||||
{value: "gateway", label: "Сервер хранения локальных данных"}]}/>
|
||||
<Description>{mode === "auto" ? "Карты используют сервер хранения локальных данных. Если сервер недоступен, подключение переключается на источник через интернет." :
|
||||
mode === "direct" ? "Карты загружаются через интернет без сохранения тайлов на этом компьютере." : "Карты загружаются только через сервер хранения локальных данных. Если сервер недоступен, загрузка приостанавливается."}</Description>
|
||||
<Select label="Маршрутизация" value={egress} disabled={busy} onChange={value=>{setEgress(value);setVerification(null);setError("");}}
|
||||
options={[{value:"",label:"Текущий маршрут"},...servers.flatMap(server=>server.services.filter(item=>item.kind==='egress').map(item=>({value:item.id,label:`${server.name} · ${server.address}`})))]}/>
|
||||
{routesError&&<Description role="alert">{routesError}</Description>}
|
||||
<TextField label={settings.token_configured ? "Новый токен Cesium ion" : "Токен Cesium ion"} type="password" value={token}
|
||||
disabled={busy} autoComplete="off" spellCheck={false} onChange={event => {setToken(event.target.value); setVerification(null); setError("");}}
|
||||
placeholder={settings.token_configured ? "Токен сохранён; заполните для замены" : "Токен"}/>
|
||||
<Description>Токен сохраняется только в Mission Core. Для прямого подключения нужен доступ к рельефу, спутниковой карте и зданиям Cesium ion.</Description>
|
||||
{showVerification && verification && <div className="cesium-service-results" role="status">{Object.entries(verification.assets).map(([id, result]) =>
|
||||
<Description key={id}>{({"1": "Рельеф", "2": "Спутниковая карта", "96188": "Здания"} as Record<string, string>)[id] ?? id}: {result.ok ? "доступ подтверждён" : cesiumServiceMessage(result.code)}</Description>)}</div>}
|
||||
</>}
|
||||
{error && <Description role="alert">{error}</Description>}
|
||||
</>}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -652,6 +652,7 @@ function CacheHealth({
|
||||
);
|
||||
}
|
||||
const { cache } = health.snapshot;
|
||||
if (!cache) return <ControlRow label="Подключение"><StatusBadge tone="neutral">Источник · без кэша</StatusBadge></ControlRow>;
|
||||
return (
|
||||
<dl className="mission-map__cache-health">
|
||||
<div>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
.cesium-service-results { display: grid; gap: var(--nodedc-space-2); }
|
||||
@@ -2,7 +2,7 @@ import {Fragment,useEffect,useState} from 'react';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
|
||||
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
|
||||
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'}){
|
||||
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'|'vps-egress'}){
|
||||
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
|
||||
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((original,index)=>{const step=connectionInstruction&&index===item.instructions.length-1?connectionInstruction:original;return <Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>;})}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {useObservationView} from '../../core/observation/useObservationView';
|
||||
import {roverModelID} from '../../core/roverScene/model';
|
||||
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
@@ -15,6 +16,9 @@ const labels:Record<string,string>={observing:'Наблюдение',preparing:'
|
||||
export function RoverView({vehicleID,name,controller:c,header,active,observation}:{vehicleID:string;name:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
|
||||
const storage=`missioncore.rover-view.v1:${vehicleID}`;
|
||||
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
|
||||
const presentation=useObservationView('rover-view',vehicleID,()=>({schema:'missioncore.rover-view/v1' as const,model:''}),async()=>{
|
||||
try{const raw=localStorage.getItem(storage);return raw?{schema:'missioncore.rover-view/v1' as const,model:roverSettings(JSON.parse(raw)).model}:null;}catch{return null;}
|
||||
});
|
||||
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||
const [editing,setEditing]=useState(false);
|
||||
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
|
||||
@@ -57,7 +61,7 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
|
||||
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
|
||||
<EditorWorkspace editing={editing&&active} title={`Ровер / ${name}`} subtitle="Редактирование сцены" onBack={()=>setEditing(false)}>
|
||||
{settings.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
{!presentation.ready?<LoadingRegion loading label="Загрузка настроек вида"/>:presentation.document.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
|
||||
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
|
||||
</LoadingRegion>:<div className="rover-view__empty"><Description>Выберите модель аппарата.</Description><Button onClick={showSettings}>Настройки вида</Button></div>}
|
||||
@@ -75,8 +79,9 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
|
||||
</EditorWorkspace>
|
||||
</div>
|
||||
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
|
||||
{presentation.error&&<><Description>{presentation.error}</Description><Button onClick={presentation.retry}>Повторить сохранение вида</Button></>}
|
||||
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
|
||||
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
|
||||
<Select label="3D-модель" disabled={!presentation.ready} value={presentation.document.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>presentation.update(v=>({...v,model}))}/>
|
||||
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
|
||||
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
|
||||
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
|
||||
|
||||
@@ -5,10 +5,10 @@ import {serverRequest,useServers,type Server} from '../../core/system/servers';
|
||||
import {vpsRequest} from '../../core/fleet/vps';
|
||||
|
||||
export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSaved}:{server?:Server;fixedKind?:'librespeed';onClose:()=>void;onSaved:()=>void}) {
|
||||
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
|
||||
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'|'egress'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
|
||||
const catalog=useServers();const [serverId,setServerId]=useState(initialServer?.id??'');
|
||||
const server=initialServer??catalog.items?.find(s=>s.id===serverId);
|
||||
const serviceName=kind==='librespeed'?'LibreSpeed':'WireGuard';
|
||||
const serviceName=kind==='egress'?'Маршрутизация трафика':kind==='librespeed'?'LibreSpeed':'WireGuard';
|
||||
const [network,setNetwork]=useState(''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');const file=useRef<HTMLInputElement>(null);
|
||||
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(r=>{if(active)setInterfaces(r.items);}).catch(()=>{});return()=>{active=false;};},[]);
|
||||
@@ -22,14 +22,14 @@ export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSav
|
||||
{!initialServer&&<Select label="VPS" value={serverId} disabled={busy} options={[{value:'',label:'Выберите VPS'},...(catalog.items??[]).map(s=>({value:s.id,label:`${s.name} · ${s.address}`}))]} onChange={id=>{setServerId(id);setDocument('');setFilename('');}}/>}
|
||||
{!initialServer&&catalog.items?.length===0&&<Description>Сначала добавьте VPS в разделе «Система → VPS».</Description>}
|
||||
{catalog.error&&!initialServer&&<Description>{catalog.error}</Description>}
|
||||
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
|
||||
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
|
||||
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'},{value:'egress',label:'Маршрутизация трафика'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
|
||||
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='egress'?'vps-egress':kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
|
||||
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
|
||||
{kind!=='arnavi'?<>
|
||||
<input ref={file} type="file" accept=".json,application/json" hidden onChange={event=>{const chosen=event.target.files?.[0];event.target.value='';if(!chosen)return;setDocument('');setFilename('');void (async()=>{if(chosen.size>16384)throw Error(`Выберите файл приглашения ${serviceName} (до 16 КБ).`);setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение {serviceName}</Button>
|
||||
{filename&&<Description>{filename}</Description>}
|
||||
<Description>Файл на VPS: {kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
|
||||
<Description>Файл на VPS: {kind==='egress'?'/var/lib/ndc-egress-vps/mission-core-egress.json':kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
|
||||
</>:<TextAreaField label="Ключ подключения ARNavi" value={document} disabled={busy} rows={4} onChange={e=>setDocument(e.target.value)} hint="Ключ находится на VPS в /opt/nodedc-mission-vps/connect.key. Действует 24 часа и используется один раз."/>}
|
||||
</SettingsCard>
|
||||
{interfaces.length>0&&<Select label="Подключение к VPS" disabled={busy} value={network} options={[{value:'',label:'Через текущую сеть'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} onChange={setNetwork}/>}
|
||||
|
||||
Reference in New Issue
Block a user