Files
opengenesislinkserver/addons/OSWebInterface/www/app.js
T

66 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
const $ = id => document.getElementById(id);
let csrf="",overview=null,jobsTimer=null,modalAction=null,latestSha=null;
const money = size => (size/(1024**2)).toFixed(1)+" MiB";
const sleepTime = s => {const h=Math.floor(s/3600),m=Math.floor((s%3600)/60);return h+"h "+m+"m"};
function notice(message, title="Hinweis", action=null) { $("modal-title").textContent=title; $("modal-message").textContent=message; $("modal").hidden=false; modalAction=action; $("modal-cancel").hidden=!action; }
$("modal-ok").onclick=()=>{ $("modal").hidden=true; if(modalAction){const a=modalAction;modalAction=null;a();} };
$("modal-cancel").onclick=()=>{$("modal").hidden=true;modalAction=null};
async function api(path, options={}) {
const headers = {...options.headers};
if(options.method&&options.method!=="GET") headers["X-OGL-CSRF"]=csrf;
const response=await fetch(path,{...options,headers,credentials:"same-origin",cache:"no-store"});
const data=await response.json().catch(()=>({error:"Ungültige Serverantwort"}));
if(!response.ok) throw new Error(data.error||"Serverfehler "+response.status);
return data;
}
function jsonPost(path,obj){return api(path,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(obj)})}
function row(...entries){const tr=document.createElement("tr");entries.forEach(e=>{const td=document.createElement("td");td.textContent=String(e??"–");tr.append(td)});return tr}
function table(target,head,rows){const t=document.createElement("table"),thead=document.createElement("thead"),tbody=document.createElement("tbody");const th=document.createElement("tr");head.forEach(h=>{let x=document.createElement("th");x.textContent=h;th.append(x)});thead.append(th);rows.forEach(r=>tbody.append(r));t.append(thead,tbody);$(target).replaceChildren(t)}
function statusCell(tr,status) {const td=tr.lastElementChild;td.replaceChildren();const span=document.createElement("span");span.className="status"+(status==="OK"?"":" bad");span.textContent=status;td.append(span)}
function renderOverview(d) {
overview=d; const regs=d.regions||[];
$("num-regions").textContent=regs.length;
$("num-avatars").textContent=regs.reduce((n,r)=>n+r.agents,0);
$("num-memory").textContent=money(d.memoryBytes);
$("num-uptime").textContent=sleepTime(d.uptimeSeconds);
table("overview-regions",["Region","Koordinaten","Größe","Avatare","Status"],regs.map(r=>{const x=row(r.name,r.location,r.size,r.agents,r.ready?"OK":"Nicht bereit");statusCell(x,r.ready?"OK":"Fehler");return x}));
table("services-table",["Dienst","Host","Port","Protokoll","Status"],(d.services||[]).map(v=>row(v.name,v.host,v.port,v.protocol,v.reachable?"Erreichbar":"Nicht erreichbar")));
const wrapper=$("region-actions");wrapper.replaceChildren();
regs.forEach(r=>{
const c=document.createElement("article");c.className="region-card";
const title=document.createElement("h3");title.textContent=r.name;
const subtitle=document.createElement("p");subtitle.textContent="Region "+r.id;
const inf=document.createElement("p");inf.textContent=r.location+" · "+r.size+" · "+r.agents+" Avatare · UDP "+r.udpPort+" · TCP "+r.httpPort;
const btn=document.createElement("button");btn.className="danger";btn.textContent="Region neu starten";
btn.onclick=()=>notice("Soll die Region „"+r.name+"“ tatsächlich neu gestartet werden? Aktive Bewohner werden unterbrochen.","Neustart bestätigen",async()=>{try{await jsonPost("/api/regions/restart",{regionId:r.id});notice("Regionsneustart wurde angefordert.");}catch(e){notice(e.message,"Fehler")}});
c.append(title,subtitle,inf,btn);wrapper.append(c);
});
const sel=$("archive-region"),v=sel.value;sel.replaceChildren();
regs.forEach(r=>{const o=document.createElement("option");o.value=r.id;o.textContent=r.name;sel.append(o)});if(regs.some(r=>r.id===v))sel.value=v;
table("ports-table",["Region","Protokoll","Port","Lokaler Listener","Öffentlicher Zugang"],(d.endpoints||[]).map(p=>{const x=row(p.name,p.protocol,p.port,p.local?"OK":"Nicht aktiv",p.publicStatus);return x}));
}
async function refresh(){try{renderOverview(await api("/api/overview"));}catch(e){notice(e.message,"Verbindung fehlgeschlagen")}}
async function loadJobs(){try{const data=await api("/api/jobs");const rows=(data.jobs||[]).map(j=>{const x=row(j.region,j.kind,j.state,j.total?(100*j.bytes/j.total).toFixed(0)+"%":"–",j.message||"–","");
if(j.download){const a=document.createElement("a");a.href="/api/oar/download?id="+encodeURIComponent(j.id);a.textContent="OAR herunterladen";a.style.color="#69c7fb";x.lastElementChild.replaceChildren(a)}return x});
table("job-table",["Region","Art","Status","Upload","Meldung","Download"],rows)}catch(e){notice(e.message,"Aufträge")}}
async function loadLogs(){try{$("log-text").textContent=(await api("/api/logs")).content;}catch(e){$("log-text").textContent=e.message}}
async function loadUpdates(){try{const live=await api("/api/updates/live-status");const status=live.update||{};$("update-live-status").textContent=live.enabled?(live.reachable?("Status: "+(status.state||"unbekannt")+" · Schritt "+(status.phase||0)+"/7 · "+(status.message||"")):live.message):"Nicht aktiviert – AllowLiveUpdates, NodeAgent und externer Updater müssen konfiguriert werden.";$("update-live-start").hidden=!(live.enabled&&live.reachable&&status.state!=="running"&&status.state!=="queued");const d=await api("/api/updates/check");latestSha=d.remote||null;$("local-sha").textContent=d.local||"Kein lokaler Git-Checkout erkannt";$("remote-sha").textContent=d.remote||"–";$("version-note").textContent=(d.newCommitCount!=null?d.newCommitCount+" Commits seit deinem Stand. ":"")+(d.error||d.note||"");const box=$("commits");box.replaceChildren();(d.commits||[]).forEach(c=>{const x=document.createElement("article");x.className="commit";const b=document.createElement("b");b.textContent=c.title;const sm=document.createElement("small");sm.textContent=c.sha.slice(0,12)+" · "+new Date(c.date).toLocaleString("de-DE");x.append(b,sm);box.append(x)})}catch(e){notice(e.message,"GitHub")}}
function showView(name){document.querySelectorAll(".view").forEach(v=>v.hidden=v.id!==name);document.querySelectorAll("nav a").forEach(v=>v.classList.toggle("active",v.dataset.view===name));const titles={overview:"Übersicht",regions:"Regionen & Aktionen",archives:"OAR-Archive",network:"Netzwerk & Ports",logs:"Simulator-Logs",updates:"Updates & GitHub"};$("page-title").textContent=titles[name]||"Übersicht";if(name==="logs")loadLogs();if(name==="archives")loadJobs();if(name==="updates")loadUpdates();}
document.querySelectorAll("nav a").forEach(a=>a.onclick=e=>{e.preventDefault();showView(a.dataset.view)});
$("login-form").onsubmit=async e=>{e.preventDefault();try{const d=await api("/api/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:$("username").value,password:$("password").value})});csrf=d.csrf;$("identity").textContent=d.name;$("login-view").hidden=true;$("dashboard").hidden=false;$("password").value="";await refresh();}catch(err){notice(err.message,err.message.includes("Access Denied")?"Access Denied":"Anmeldung fehlgeschlagen")}};
$("refresh").onclick=refresh;
$("logout").onclick=async()=>{try{await api("/api/logout",{method:"POST"})}finally{csrf="";$("dashboard").hidden=true;$("login-view").hidden=false}};
$("oar-file").onchange=()=>{$("selected-file").textContent=$("oar-file").files[0]?.name||""};
$("oar-export").onclick=async()=>{try{const d=await jsonPost("/api/oar/export",{regionId:$("archive-region").value});notice("OAR-Sicherung gestartet: "+d.id);await loadJobs()}catch(e){notice(e.message,"OAR Export")}};
$("oar-import").onclick=()=>{const f=$("oar-file").files[0];if(!f){notice("Bitte zuerst eine .oar-Datei auswählen.");return;}if(f.size>2*1024**3){notice("Die Datei überschreitet 2 GiB.");return;}notice("ACHTUNG: OAR-Import kann alle Objekte und Gelände der gewählten Region überschreiben. Jetzt „"+f.name+"“ importieren?","OAR-Import bestätigen",async()=>{try{const d=await new Promise((resolve,reject)=>{const xhr=new XMLHttpRequest();xhr.open("POST","/api/oar/import?region="+encodeURIComponent($("archive-region").value));xhr.withCredentials=true;xhr.setRequestHeader("Content-Type","application/octet-stream");xhr.setRequestHeader("X-OGL-CSRF",csrf);xhr.upload.onprogress=e=>{if(e.lengthComputable)$("selected-file").textContent="Upload: "+Math.round(e.loaded*100/e.total)+"% ("+f.name+")";};xhr.onerror=()=>reject(new Error("Netzwerkfehler beim OAR Upload"));xhr.onload=()=>{let v;try{v=JSON.parse(xhr.responseText||"{}")}catch{v={error:"Ungültige Serverantwort"}}xhr.status>=200&&xhr.status<300?resolve(v):reject(new Error(v.error||"Upload fehlgeschlagen"))};xhr.send(f)});notice("Import angenommen: "+d.id+". Status im Auftragsbereich sichtbar.");await loadJobs()}catch(e){notice(e.message,"OAR Import")}})};
$("update-live-start").onclick=()=>notice("ACHTUNG: Der unabhängige Updater sichert lokale Konfigurationen und führt anschließend git reset --hard origin/main sowie einen .NET-10-Build aus. Die laufenden Binaries können währenddessen verändert werden. Ein Wartungsfenster und ein manueller Simulator-Neustart sind erforderlich. Update jetzt wirklich starten?","Live-Update bestätigen",async()=>{try{const d=await api("/api/updates/live-start",{method:"POST"});notice(d.note||"Live-Update angefordert.","Auftrag angenommen");await loadUpdates()}catch(e){notice(e.message,"Live-Update fehlgeschlagen")}});
$("update-stage").onclick=()=>{if(!latestSha){notice("Bitte zuerst GitHub prüfen.");return}notice("Commit "+latestSha.slice(0,12)+" herunterladen und vertrauliche Konfiguration lokal sichern? Es werden keine laufenden Programmdateien verändert.","Update vorbereiten",async()=>{try{const d=await jsonPost("/api/updates/stage",{sha:latestSha});notice(d.note+" Sicherung: "+d.backup,"Download abgeschlossen")}catch(e){notice(e.message,"Update fehlgeschlagen")}})};
$("logs-refresh").onclick=loadLogs;$("updates-refresh").onclick=loadUpdates;$("jobs-refresh").onclick=loadJobs;
async function bootstrap(){try{const d=await api("/api/me");csrf=d.csrf;$("identity").textContent=d.name;$("dashboard").hidden=false;$("login-view").hidden=true;await refresh()}catch{}}bootstrap();
setInterval(()=>{if(!$("dashboard").hidden){refresh();if(!$("archives").hidden)loadJobs()}},30000);
setInterval(()=>{if(!$("dashboard").hidden&&!$("archives").hidden)loadJobs()},4000);
setInterval(()=>{if(!$("dashboard").hidden&&!$("updates").hidden)api("/api/updates/live-status").then(d=>{const s=d.update||{};$("update-live-status").textContent=d.enabled?(d.reachable?("Status: "+(s.state||"?")+" · Schritt "+(s.phase||0)+"/7 · "+(s.message||"")):d.message):"Nicht aktiviert";$("update-live-start").hidden=!(d.enabled&&d.reachable&&s.state!=="running"&&s.state!=="queued")}).catch(()=>{})},10000);