This commit is contained in:
2026-03-06 22:21:44 +01:00
parent 5047dd8a05
commit 06e240cc22
10 changed files with 140 additions and 85 deletions

View File

@@ -0,0 +1,308 @@
(() => {
const tabBar = document.querySelector('[data-console-tab-bar]');
const tabPanels = document.querySelector('[data-console-tab-panels]');
if (!tabBar || !tabPanels) return;
let tabCount = 0;
const idleMs = 5 * 60 * 1000;
const idleTimers = new Map();
const storageKey = 'pi_control_console_tabs';
const saveTabs = () => {
const tabs = [];
tabBar.querySelectorAll('.console-tab').forEach((btn) => {
const id = btn.dataset.tabId;
const panel = tabPanels.querySelector(`.console-panel[data-tab-id="${id}"]`);
const iframe = panel ? panel.querySelector('iframe') : null;
if (iframe && iframe.src) {
tabs.push({
label: btn.firstChild ? btn.firstChild.textContent : btn.textContent,
url: iframe.src,
openedAt: Date.now(),
});
}
});
localStorage.setItem(storageKey, JSON.stringify(tabs));
};
const activateTab = (id) => {
tabBar.querySelectorAll('.console-tab').forEach((btn) => {
btn.classList.toggle('is-active', btn.dataset.tabId === id);
});
tabPanels.querySelectorAll('.console-panel').forEach((panel) => {
panel.classList.toggle('is-active', panel.dataset.tabId === id);
});
};
const getActiveIframe = () => {
const activePanel = tabPanels.querySelector('.console-panel.is-active');
if (!activePanel) return null;
return activePanel.querySelector('iframe');
};
const trySendToIframe = (iframe, command) => {
if (!iframe) return false;
try {
const win = iframe.contentWindow;
if (!win) return false;
const term = win.term || win.xterm || win.terminal;
if (term && typeof term.write === 'function') {
term.write(command + '\r');
return true;
}
} catch (e) {
return false;
}
return false;
};
const openTab = (label, url, persist = true) => {
const id = `tab-${++tabCount}`;
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'console-tab';
btn.textContent = label || 'Konsole';
btn.dataset.tabId = id;
btn.addEventListener('click', () => activateTab(id));
const closeBtn = document.createElement('span');
closeBtn.className = 'console-tab-close';
closeBtn.textContent = '×';
closeBtn.addEventListener('click', (e) => {
e.stopPropagation();
const panel = tabPanels.querySelector(`.console-panel[data-tab-id="${id}"]`);
if (panel) panel.remove();
btn.remove();
idleTimers.delete(id);
saveTabs();
const next = tabBar.querySelector('.console-tab');
if (next) activateTab(next.dataset.tabId);
});
btn.appendChild(closeBtn);
const panel = document.createElement('div');
panel.className = 'console-panel';
panel.dataset.tabId = id;
panel.innerHTML = `<iframe src="${url}" title="${label || 'Konsole'}"></iframe>`;
tabBar.appendChild(btn);
tabPanels.appendChild(panel);
activateTab(id);
if (persist) saveTabs();
const iframe = panel.querySelector('iframe');
const markActive = () => {
idleTimers.set(id, Date.now());
};
idleTimers.set(id, Date.now());
iframe.addEventListener('load', () => {
try {
const doc = iframe.contentWindow.document;
['keydown', 'mousedown', 'wheel', 'touchstart'].forEach((evt) => {
doc.addEventListener(evt, markActive, { passive: true });
});
const observer = new MutationObserver(markActive);
observer.observe(doc.body, { childList: true, subtree: true, characterData: true });
} catch (e) {
// cross-origin or blocked; rely on timer only
}
});
const idleCheck = setInterval(() => {
const last = idleTimers.get(id) || 0;
if (Date.now() - last > idleMs) {
const panelEl = tabPanels.querySelector(`.console-panel[data-tab-id="${id}"]`);
const btnEl = tabBar.querySelector(`.console-tab[data-tab-id="${id}"]`);
if (panelEl) panelEl.remove();
if (btnEl) btnEl.remove();
idleTimers.delete(id);
saveTabs();
clearInterval(idleCheck);
const next = tabBar.querySelector('.console-tab');
if (next) activateTab(next.dataset.tabId);
}
}, 10000);
};
document.querySelectorAll('.console-launch').forEach((el) => {
const url = el.dataset.url;
const host = el.dataset.host || 'Konsole';
if (url) {
openTab(host, url);
}
el.remove();
});
const showRestoreNotice = (text) => {
const notice = document.querySelector('[data-console-notice]');
if (!notice) return;
notice.textContent = text;
notice.style.display = 'block';
};
try {
const raw = localStorage.getItem(storageKey);
if (raw) {
const tabs = JSON.parse(raw);
if (Array.isArray(tabs)) {
const now = Date.now();
tabs.forEach((t) => {
if (t && t.url) {
if (t.openedAt && now - t.openedAt > (10 * 60 * 1000)) {
showRestoreNotice('Token abgelaufen, bitte Konsole neu öffnen.');
return;
}
openTab(t.label || 'Konsole', t.url, false);
}
});
}
}
} catch (e) {
// ignore
}
const queueBody = document.querySelector('[data-queue-body]');
const countdownEl = document.querySelector('[data-queue-countdown]');
const refreshBtn = document.querySelector('[data-queue-refresh]');
if (!queueBody || !countdownEl) return;
let remaining = 10;
const fetchQueue = async () => {
const url = new URL(window.location.href);
url.searchParams.set('queue_json', '1');
try {
const res = await fetch(url.toString(), { cache: 'no-store' });
if (!res.ok) return;
const data = await res.json();
if (data && data.html) {
queueBody.innerHTML = data.html;
}
remaining = data && data.next ? data.next : 10;
} catch (e) {
// ignore
}
};
const tick = () => {
remaining -= 1;
if (remaining <= 0) {
fetchQueue();
remaining = 10;
}
countdownEl.textContent = String(remaining);
};
setInterval(tick, 1000);
if (refreshBtn) {
refreshBtn.addEventListener('click', () => {
fetchQueue();
remaining = 10;
countdownEl.textContent = String(remaining);
});
}
const consoleForm = document.querySelector('[data-console-form]');
const consoleError = document.querySelector('[data-console-error]');
const consoleNotice = document.querySelector('[data-console-notice]');
const tokenEl = document.querySelector('[data-console-token]');
if (consoleForm) {
consoleForm.addEventListener('submit', (e) => e.preventDefault());
const presetSelect = consoleForm.querySelector('select[name="terminal_preset_id"]');
const commandTextarea = consoleForm.querySelector('textarea[name="terminal_command_text"]');
if (presetSelect && commandTextarea) {
presetSelect.addEventListener('change', () => {
const opt = presetSelect.selectedOptions[0];
const cmd = opt && opt.dataset && opt.dataset.command ? opt.dataset.command : '';
if (cmd) {
commandTextarea.value = cmd;
}
});
}
const submitOpen = async () => {
const formData = new FormData(consoleForm);
if (presetSelect) formData.set('terminal_preset_id', '');
const url = new URL(window.location.href);
url.searchParams.set('open_console_json', '1');
const res = await fetch(url.toString(), { method: 'POST', body: formData, cache: 'no-store' });
const data = await res.json();
if (!data.ok) {
if (consoleError) {
consoleError.textContent = data.error || 'Fehler beim Öffnen der Konsole.';
consoleError.style.display = 'block';
}
return;
}
if (consoleError) consoleError.style.display = 'none';
if (consoleNotice) consoleNotice.style.display = 'none';
if (tokenEl) tokenEl.textContent = data.token || '';
if (data.url) openTab(data.host || 'Konsole', data.url);
};
const submitRun = async () => {
const formData = new FormData(consoleForm);
if (presetSelect) formData.set('terminal_preset_id', '');
const url = new URL(window.location.href);
url.searchParams.set('run_command_json', '1');
const res = await fetch(url.toString(), { method: 'POST', body: formData, cache: 'no-store' });
const data = await res.json();
if (!data.ok) {
if (consoleError) {
consoleError.textContent = data.error || 'Fehler beim Ausführen.';
consoleError.style.display = 'block';
}
return;
}
if (consoleError) consoleError.style.display = 'none';
if (consoleNotice) {
consoleNotice.textContent = data.notice || '';
consoleNotice.style.display = 'block';
}
fetchQueue();
remaining = 10;
countdownEl.textContent = String(remaining);
};
const openBtn = consoleForm.querySelector('[data-open-console]');
const runBtn = consoleForm.querySelector('[data-run-command]');
const sendBtn = consoleForm.querySelector('[data-send-active]');
if (openBtn) {
openBtn.addEventListener('click', (e) => {
e.preventDefault();
submitOpen();
});
}
if (runBtn) {
runBtn.addEventListener('click', (e) => {
e.preventDefault();
submitRun();
});
}
if (sendBtn) {
sendBtn.addEventListener('click', (e) => {
e.preventDefault();
if (!commandTextarea || !commandTextarea.value.trim()) {
if (consoleError) {
consoleError.textContent = 'Bitte zuerst einen Befehl eingeben.';
consoleError.style.display = 'block';
}
return;
}
const iframe = getActiveIframe();
const ok = trySendToIframe(iframe, commandTextarea.value.trim());
if (!ok) {
if (consoleNotice) {
consoleNotice.textContent = 'Aktive Konsole nicht steuerbar Befehl wird in neuer Konsole ausgeführt.';
consoleNotice.style.display = 'block';
}
submitOpen();
return;
}
if (consoleError) consoleError.style.display = 'none';
});
}
}
})();

View File

@@ -0,0 +1,74 @@
.form-card { padding: 14px; }
.form-grid { display: grid; gap: 12px; }
.form-field { display: grid; gap: 6px; }
.form-field input,
.form-field select,
.form-field textarea { width: 100%; }
.icon-button {
border: 1px solid var(--line);
background: var(--panel-2);
border-radius: 999px;
padding: 4px 10px;
cursor: pointer;
font-weight: 700;
}
.icon-button:hover { background: var(--panel); }
.console-tabs {
border: 1px solid var(--line);
border-radius: 14px;
overflow: hidden;
background: #0b0f17;
}
.console-tab-bar {
display: flex;
gap: 6px;
flex-wrap: wrap;
padding: 8px;
background: #0f1624;
border-bottom: 1px solid rgba(255,255,255,0.08);
}
.console-tab {
background: transparent;
color: #c9d3e3;
border: 1px solid transparent;
border-radius: 10px;
padding: 6px 10px;
cursor: pointer;
font-weight: 600;
display: inline-flex;
align-items: center;
gap: 8px;
}
.console-tab.is-active {
border-color: rgba(255,255,255,0.2);
background: rgba(255,255,255,0.08);
color: #ffffff;
}
.console-tab-panels {
min-height: 420px;
}
.console-tab-close {
display: inline-flex;
width: 18px;
height: 18px;
align-items: center;
justify-content: center;
border-radius: 999px;
background: rgba(255,255,255,0.12);
color: #ffffff;
font-size: 0.8rem;
line-height: 1;
}
.console-tab-close:hover {
background: rgba(255,255,255,0.25);
}
.console-panel { display: none; }
.console-panel.is-active { display: block; }
.console-panel iframe {
width: 100%;
height: 520px;
border: 0;
background: #0b0f17;
}

View File

@@ -94,6 +94,7 @@ $mm->registerFunction($moduleName, 'ensure_schema', function () use ($moduleName
token VARCHAR(64) NOT NULL UNIQUE,
host_id INTEGER NOT NULL,
provider VARCHAR(20) NOT NULL DEFAULT 'ttyd',
command_text TEXT NULL,
created_by VARCHAR(120) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL,
@@ -139,6 +140,7 @@ $mm->registerFunction($moduleName, 'ensure_schema', function () use ($moduleName
token VARCHAR(64) NOT NULL UNIQUE,
host_id INTEGER NOT NULL,
provider VARCHAR(20) NOT NULL DEFAULT 'ttyd',
command_text TEXT NULL,
created_by VARCHAR(120) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at DATETIME NOT NULL,
@@ -154,6 +156,7 @@ $mm->registerFunction($moduleName, 'ensure_schema', function () use ($moduleName
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN IF NOT EXISTS timeout_sec INTEGER NULL");
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN IF NOT EXISTS started_at TIMESTAMP NULL");
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN IF NOT EXISTS finished_at TIMESTAMP NULL");
$pdo->exec("ALTER TABLE {$sessionTable} ADD COLUMN IF NOT EXISTS command_text TEXT NULL");
} else {
$columns = [];
$stmt = $pdo->query('PRAGMA table_info(' . $cmdTable . ')');
@@ -184,6 +187,15 @@ $mm->registerFunction($moduleName, 'ensure_schema', function () use ($moduleName
if (empty($columns['finished_at'])) {
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN finished_at DATETIME NULL");
}
$columns = [];
$stmt = $pdo->query('PRAGMA table_info(' . $sessionTable . ')');
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $col) {
$columns[$col['name']] = true;
}
if (empty($columns['command_text'])) {
$pdo->exec("ALTER TABLE {$sessionTable} ADD COLUMN command_text TEXT NULL");
}
}
// Seed default commands (only when empty)

View File

@@ -0,0 +1,30 @@
<?php
$file = (string)($_GET['file'] ?? '');
$base = realpath(__DIR__ . '/../assets');
$map = [
'pi_control.css' => $base . '/pi_control.css',
'console.js' => $base . '/console.js',
];
if (!isset($map[$file])) {
http_response_code(404);
exit('Not found');
}
$path = $map[$file];
if (!$base || !is_file($path) || !str_starts_with($path, $base)) {
http_response_code(404);
exit('Not found');
}
$ext = pathinfo($path, PATHINFO_EXTENSION);
if ($ext === 'css') {
header('Content-Type: text/css; charset=utf-8');
} elseif ($ext === 'js') {
header('Content-Type: application/javascript; charset=utf-8');
} else {
header('Content-Type: application/octet-stream');
}
readfile($path);
exit;

View File

@@ -2,6 +2,10 @@
$pdo = module_fn('pi_control', 'pdo');
module_fn('pi_control', 'ensure_schema');
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
$assets = app()->assets();
if ($assets) {
$assets->addStyle('/module/pi_control/asset?file=pi_control.css');
}
$notice = null;
$error = null;

View File

@@ -14,7 +14,8 @@ $terminalHostLabel = null;
$settings = modules()->settings('pi_control');
$assets = app()->assets();
if ($assets) {
$assets->addScript('/assets/js/pi_control_console.js', 'footer', true);
$assets->addStyle('/module/pi_control/asset?file=pi_control.css');
$assets->addScript('/module/pi_control/asset?file=console.js', 'footer', true);
}
$ttydUrl = trim((string)($settings['ttyd_url'] ?? '/ttyd'));
$defaultProvider = 'ttyd';
@@ -105,22 +106,20 @@ if (isset($_GET['open_console_json'])) {
$token = bin2hex(random_bytes(24));
$terminalToken = $token;
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('sessions') . ' (token, host_id, provider, created_by, expires_at)
VALUES (:token, :host_id, :provider, :created_by, ' . $expiresSql . ')'
'INSERT INTO ' . $table('sessions') . ' (token, host_id, provider, command_text, created_by, expires_at)
VALUES (:token, :host_id, :provider, :command_text, :created_by, ' . $expiresSql . ')'
);
$commandToRun = $presetCommand !== '' ? $presetCommand : $rawCommand;
$stmt->execute([
'token' => $token,
'host_id' => $hostId,
'provider' => 'ttyd',
'command_text' => $commandToRun !== '' ? $commandToRun : null,
'created_by' => auth_display_name() ?: null,
]);
$sep = str_contains($ttydUrl, '?') ? '&' : '?';
$terminalUrl = rtrim($ttydUrl, '/') . '/' . $sep . 'arg=' . rawurlencode($token);
$commandToRun = $presetCommand !== '' ? $presetCommand : $rawCommand;
if ($commandToRun !== '') {
$terminalUrl .= '&arg=' . rawurlencode(base64_encode($commandToRun));
}
foreach ($hosts as $h) {
if ((int)$h['id'] === $hostId) {
$terminalHostLabel = (string)($h['name'] ?? $h['host']);
@@ -281,7 +280,7 @@ $runs = $pdo->query(
<textarea name="terminal_command_text" rows="2" placeholder="Optional: Befehl direkt ausführen"></textarea>
</label>
<div style="display:flex; gap:10px; flex-wrap:wrap;">
<button class="cta-button" type="button" data-open-console>Konsole öffnen</button>
<button class="cta-button" type="button" data-open-console>Neue Konsole öffnen</button>
<button class="nav-link" type="button" data-run-command>Im Hintergrund ausführen</button>
<button class="nav-link" type="button" data-send-active>In aktiver Konsole ausführen</button>
</div>

View File

@@ -2,6 +2,10 @@
$pdo = module_fn('pi_control', 'pdo');
module_fn('pi_control', 'ensure_schema');
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
$assets = app()->assets();
if ($assets) {
$assets->addStyle('/module/pi_control/asset?file=pi_control.css');
}
$notice = null;
$error = null;

View File

@@ -59,6 +59,12 @@ if (!$host) {
$pdo->prepare('UPDATE ' . $table('sessions') . ' SET last_used_at = ' . $nowSql . ' WHERE id = :id')
->execute(['id' => (int)$session['id']]);
$commandText = (string)($session['command_text'] ?? '');
if ($commandText !== '') {
$pdo->prepare('UPDATE ' . $table('sessions') . ' SET command_text = NULL WHERE id = :id')
->execute(['id' => (int)$session['id']]);
}
echo json_encode([
'ok' => true,
'host' => [
@@ -70,5 +76,6 @@ echo json_encode([
'key_path' => (string)($host['key_path'] ?? ''),
'password' => (string)($host['password'] ?? ''),
],
'command' => $commandText,
]);
exit;