New desktop
This commit is contained in:
162
temp/nexus-module-import/modules/pi_control/assets/commands.js
Normal file
162
temp/nexus-module-import/modules/pi_control/assets/commands.js
Normal file
@@ -0,0 +1,162 @@
|
||||
(() => {
|
||||
const form = document.querySelector('[data-command-form]');
|
||||
const list = document.querySelector('[data-command-list]');
|
||||
if (!form) return;
|
||||
|
||||
const idInput = form.querySelector('input[name="id"]');
|
||||
const labelInput = form.querySelector('input[name="label"]');
|
||||
const commandInput = form.querySelector('textarea[name="command"]');
|
||||
const timeoutInput = form.querySelector('input[name="timeout_sec"]');
|
||||
const adminInput = form.querySelector('input[name="admin_only"]');
|
||||
const submitBtn = form.querySelector('[data-command-submit]');
|
||||
const cancelBtn = form.querySelector('[data-command-cancel]');
|
||||
const modal = document.querySelector('[data-command-modal]');
|
||||
const modalTitle = document.querySelector('[data-command-modal-title]');
|
||||
const closeBtn = document.querySelector('[data-command-close]');
|
||||
const newBtn = document.querySelector('[data-command-new]');
|
||||
const unsavedBar = document.querySelector('[data-command-unsaved]');
|
||||
const discardBtn = document.querySelector('[data-command-discard]');
|
||||
|
||||
let initialSnapshot = '';
|
||||
|
||||
const resetForm = () => {
|
||||
if (idInput) idInput.value = '';
|
||||
if (labelInput) labelInput.value = '';
|
||||
if (commandInput) commandInput.value = '';
|
||||
if (timeoutInput) timeoutInput.value = '';
|
||||
if (adminInput) adminInput.checked = false;
|
||||
if (submitBtn) submitBtn.textContent = 'Speichern';
|
||||
if (unsavedBar) unsavedBar.style.display = 'none';
|
||||
};
|
||||
|
||||
const snapshot = () => {
|
||||
return JSON.stringify({
|
||||
id: idInput ? idInput.value : '',
|
||||
label: labelInput ? labelInput.value : '',
|
||||
command: commandInput ? commandInput.value : '',
|
||||
timeout: timeoutInput ? timeoutInput.value : '',
|
||||
admin: adminInput ? adminInput.checked : false,
|
||||
});
|
||||
};
|
||||
|
||||
const isDirty = () => snapshot() !== initialSnapshot;
|
||||
|
||||
const openModal = () => {
|
||||
if (!modal) return;
|
||||
modal.classList.add('is-open');
|
||||
modal.setAttribute('aria-hidden', 'false');
|
||||
initialSnapshot = snapshot();
|
||||
};
|
||||
|
||||
const closeModal = (force = false) => {
|
||||
if (!modal) return;
|
||||
if (!force && isDirty()) {
|
||||
if (unsavedBar) unsavedBar.style.display = 'flex';
|
||||
return;
|
||||
}
|
||||
modal.classList.remove('is-open');
|
||||
modal.setAttribute('aria-hidden', 'true');
|
||||
if (unsavedBar) unsavedBar.style.display = 'none';
|
||||
};
|
||||
|
||||
document.querySelectorAll('[data-command-edit]').forEach((btn) => {
|
||||
btn.addEventListener('click', () => {
|
||||
const item = btn.closest('.command-item');
|
||||
if (!item) return;
|
||||
if (idInput) idInput.value = item.dataset.commandId || '';
|
||||
if (labelInput) labelInput.value = item.dataset.label || '';
|
||||
if (commandInput) commandInput.value = item.dataset.command || '';
|
||||
if (timeoutInput) timeoutInput.value = item.dataset.timeout || '';
|
||||
if (adminInput) adminInput.checked = item.dataset.admin === '1';
|
||||
if (submitBtn) submitBtn.textContent = 'Aktualisieren';
|
||||
if (modalTitle) modalTitle.textContent = 'Befehl bearbeiten';
|
||||
const details = btn.closest('details');
|
||||
if (details) details.removeAttribute('open');
|
||||
openModal();
|
||||
});
|
||||
});
|
||||
|
||||
if (cancelBtn) {
|
||||
cancelBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
resetForm();
|
||||
});
|
||||
}
|
||||
|
||||
if (newBtn) {
|
||||
newBtn.addEventListener('click', () => {
|
||||
resetForm();
|
||||
if (modalTitle) modalTitle.textContent = 'Neuer Befehl';
|
||||
openModal();
|
||||
});
|
||||
}
|
||||
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', () => closeModal(false));
|
||||
}
|
||||
|
||||
if (discardBtn) {
|
||||
discardBtn.addEventListener('click', () => {
|
||||
resetForm();
|
||||
closeModal(true);
|
||||
});
|
||||
}
|
||||
|
||||
form.addEventListener('input', () => {
|
||||
if (unsavedBar && isDirty()) {
|
||||
unsavedBar.style.display = 'flex';
|
||||
}
|
||||
});
|
||||
|
||||
if (!list) return;
|
||||
|
||||
let dragging = null;
|
||||
|
||||
list.querySelectorAll('.command-item').forEach((item) => {
|
||||
item.addEventListener('dragstart', () => {
|
||||
dragging = item;
|
||||
item.classList.add('is-dragging');
|
||||
});
|
||||
item.addEventListener('dragend', () => {
|
||||
item.classList.remove('is-dragging');
|
||||
dragging = null;
|
||||
saveOrder();
|
||||
});
|
||||
});
|
||||
|
||||
list.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
if (!dragging) return;
|
||||
const after = getDragAfterElement(list, e.clientY);
|
||||
if (after == null) {
|
||||
list.appendChild(dragging);
|
||||
} else if (after !== dragging) {
|
||||
list.insertBefore(dragging, after);
|
||||
}
|
||||
});
|
||||
|
||||
const getDragAfterElement = (container, y) => {
|
||||
const elements = [...container.querySelectorAll('.command-item:not(.is-dragging)')];
|
||||
return elements.reduce(
|
||||
(closest, child) => {
|
||||
const box = child.getBoundingClientRect();
|
||||
const offset = y - box.top - box.height / 2;
|
||||
if (offset < 0 && offset > closest.offset) {
|
||||
return { offset, element: child };
|
||||
}
|
||||
return closest;
|
||||
},
|
||||
{ offset: Number.NEGATIVE_INFINITY, element: null }
|
||||
).element;
|
||||
};
|
||||
|
||||
const saveOrder = () => {
|
||||
const order = [...list.querySelectorAll('.command-item')].map((el) => el.dataset.commandId);
|
||||
fetch(window.location.pathname + '?reorder_json=1', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ order }),
|
||||
cache: 'no-store',
|
||||
}).catch(() => {});
|
||||
};
|
||||
})();
|
||||
417
temp/nexus-module-import/modules/pi_control/assets/console.js
Normal file
417
temp/nexus-module-import/modules/pi_control/assets/console.js
Normal file
@@ -0,0 +1,417 @@
|
||||
(() => {
|
||||
// Disable any beforeunload prompts on this page
|
||||
window.onbeforeunload = null;
|
||||
window.addEventListener(
|
||||
'beforeunload',
|
||||
(e) => {
|
||||
e.stopImmediatePropagation();
|
||||
},
|
||||
{ capture: true }
|
||||
);
|
||||
const tabBar = document.querySelector('[data-console-tab-bar]');
|
||||
const tabPanels = document.querySelector('[data-console-tab-panels]');
|
||||
if (!tabBar || !tabPanels) return;
|
||||
|
||||
const consoleFab = document.querySelector('[data-console-fab]');
|
||||
const consoleModal = document.querySelector('[data-console-modal]');
|
||||
const consoleClose = document.querySelector('[data-console-close]');
|
||||
|
||||
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));
|
||||
if (consoleFab) {
|
||||
consoleFab.classList.toggle('is-visible', tabs.length > 0);
|
||||
}
|
||||
};
|
||||
|
||||
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\n');
|
||||
return true;
|
||||
}
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const openModal = () => {
|
||||
if (!consoleModal) return;
|
||||
consoleModal.classList.add('is-open');
|
||||
consoleModal.setAttribute('aria-hidden', 'false');
|
||||
};
|
||||
const closeModal = () => {
|
||||
if (!consoleModal) return;
|
||||
consoleModal.classList.remove('is-open');
|
||||
consoleModal.setAttribute('aria-hidden', 'true');
|
||||
};
|
||||
|
||||
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();
|
||||
openModal();
|
||||
|
||||
const iframe = panel.querySelector('iframe');
|
||||
const markActive = () => {
|
||||
idleTimers.set(id, Date.now());
|
||||
};
|
||||
idleTimers.set(id, Date.now());
|
||||
|
||||
iframe.addEventListener('load', () => {
|
||||
try {
|
||||
const disableBeforeUnload = (win) => {
|
||||
if (!win) return;
|
||||
try {
|
||||
win.onbeforeunload = null;
|
||||
win.addEventListener(
|
||||
'beforeunload',
|
||||
(e) => {
|
||||
e.stopImmediatePropagation();
|
||||
},
|
||||
{ capture: true }
|
||||
);
|
||||
if (win.document) {
|
||||
win.document.onbeforeunload = null;
|
||||
win.document.addEventListener(
|
||||
'beforeunload',
|
||||
(e) => {
|
||||
e.stopImmediatePropagation();
|
||||
},
|
||||
{ capture: true }
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
disableBeforeUnload(iframe.contentWindow);
|
||||
setInterval(() => disableBeforeUnload(iframe.contentWindow), 2000);
|
||||
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);
|
||||
}
|
||||
});
|
||||
if (consoleFab && tabs.length > 0) {
|
||||
consoleFab.classList.add('is-visible');
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
if (consoleFab) {
|
||||
consoleFab.addEventListener('click', openModal);
|
||||
}
|
||||
if (consoleClose) {
|
||||
consoleClose.addEventListener('click', closeModal);
|
||||
}
|
||||
if (consoleModal) {
|
||||
consoleModal.addEventListener('click', (e) => {
|
||||
if (e.target === consoleModal) closeModal();
|
||||
});
|
||||
}
|
||||
|
||||
const queueBody = document.querySelector('[data-queue-body]');
|
||||
const countdownEl = document.querySelector('[data-queue-countdown]');
|
||||
const refreshBtn = document.querySelector('[data-queue-refresh]');
|
||||
const queueBtn = document.querySelector('[data-queue-button]');
|
||||
const queueCount = document.querySelector('[data-queue-count]');
|
||||
const queueModal = document.querySelector('[data-queue-modal]');
|
||||
const queueClose = document.querySelector('[data-queue-close]');
|
||||
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;
|
||||
}
|
||||
if (queueCount && typeof data.count === 'number') {
|
||||
queueCount.textContent = String(data.count);
|
||||
queueCount.style.display = data.count > 0 ? 'inline-flex' : 'none';
|
||||
}
|
||||
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);
|
||||
fetchQueue();
|
||||
if (refreshBtn) {
|
||||
refreshBtn.addEventListener('click', () => {
|
||||
fetchQueue();
|
||||
remaining = 10;
|
||||
countdownEl.textContent = String(remaining);
|
||||
});
|
||||
}
|
||||
|
||||
if (queueBtn && queueModal) {
|
||||
queueBtn.addEventListener('click', () => {
|
||||
queueModal.classList.add('is-open');
|
||||
queueModal.setAttribute('aria-hidden', 'false');
|
||||
fetchQueue();
|
||||
});
|
||||
}
|
||||
if (queueClose && queueModal) {
|
||||
queueClose.addEventListener('click', () => {
|
||||
queueModal.classList.remove('is-open');
|
||||
queueModal.setAttribute('aria-hidden', 'true');
|
||||
});
|
||||
}
|
||||
if (queueModal) {
|
||||
queueModal.addEventListener('click', (e) => {
|
||||
if (e.target === queueModal) {
|
||||
queueModal.classList.remove('is-open');
|
||||
queueModal.setAttribute('aria-hidden', 'true');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
queueBody.addEventListener('click', async (e) => {
|
||||
const btn = e.target.closest('[data-queue-action]');
|
||||
if (!btn) return;
|
||||
const runId = btn.getAttribute('data-run-id');
|
||||
const action = btn.getAttribute('data-queue-action');
|
||||
if (!runId || !action) return;
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('queue_action_json', '1');
|
||||
const formData = new FormData();
|
||||
formData.set('run_id', runId);
|
||||
formData.set('action', action);
|
||||
try {
|
||||
const res = await fetch(url.toString(), { method: 'POST', body: formData, cache: 'no-store' });
|
||||
const data = await res.json();
|
||||
if (!data.ok) {
|
||||
if (consoleNotice) {
|
||||
consoleNotice.textContent = data.error || 'Aktion fehlgeschlagen.';
|
||||
consoleNotice.style.display = 'block';
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (consoleNotice) {
|
||||
consoleNotice.textContent = 'Aktion fehlgeschlagen.';
|
||||
consoleNotice.style.display = 'block';
|
||||
}
|
||||
}
|
||||
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]');
|
||||
if (openBtn) {
|
||||
openBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
submitOpen();
|
||||
});
|
||||
}
|
||||
if (runBtn) {
|
||||
runBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
submitRun();
|
||||
});
|
||||
}
|
||||
// send-active removed
|
||||
}
|
||||
})();
|
||||
286
temp/nexus-module-import/modules/pi_control/assets/hosts.js
Normal file
286
temp/nexus-module-import/modules/pi_control/assets/hosts.js
Normal file
@@ -0,0 +1,286 @@
|
||||
(() => {
|
||||
const form = document.querySelector('[data-host-form]');
|
||||
if (!form) return;
|
||||
|
||||
const idInput = form.querySelector('input[name="id"]');
|
||||
const nameInput = form.querySelector('input[name="name"]');
|
||||
const hostInput = form.querySelector('input[name="host"]');
|
||||
const portInput = form.querySelector('input[name="port"]');
|
||||
const userInput = form.querySelector('input[name="username"]');
|
||||
const authSelect = form.querySelector('select[name="auth_type"]');
|
||||
const keyInput = form.querySelector('input[name="key_path"]');
|
||||
const passInput = form.querySelector('input[name="password"]');
|
||||
const imageInput = form.querySelector('input[name="image_url"]');
|
||||
const submitBtn = form.querySelector('[data-host-submit]');
|
||||
const modal = document.querySelector('[data-host-modal]');
|
||||
const modalTitle = document.querySelector('[data-host-modal-title]');
|
||||
const closeBtn = document.querySelector('[data-host-close]');
|
||||
const newBtn = document.querySelector('[data-host-new]');
|
||||
const checkAllBtn = document.querySelector('[data-host-check-all]');
|
||||
const cancelBtn = form.querySelector('[data-host-cancel]');
|
||||
|
||||
let initialSnapshot = '';
|
||||
|
||||
const resetForm = () => {
|
||||
if (idInput) idInput.value = '';
|
||||
if (nameInput) nameInput.value = '';
|
||||
if (hostInput) hostInput.value = '';
|
||||
if (portInput) portInput.value = '22';
|
||||
if (userInput) userInput.value = '';
|
||||
if (authSelect) authSelect.value = 'key';
|
||||
if (keyInput) keyInput.value = '';
|
||||
if (passInput) passInput.value = '';
|
||||
if (imageInput) imageInput.value = '';
|
||||
if (submitBtn) submitBtn.textContent = 'Speichern';
|
||||
if (modal && modal.classList.contains('is-open')) {
|
||||
initialSnapshot = snapshot();
|
||||
}
|
||||
};
|
||||
|
||||
const snapshot = () => {
|
||||
return JSON.stringify({
|
||||
id: idInput ? idInput.value : '',
|
||||
name: nameInput ? nameInput.value : '',
|
||||
host: hostInput ? hostInput.value : '',
|
||||
port: portInput ? portInput.value : '',
|
||||
user: userInput ? userInput.value : '',
|
||||
auth: authSelect ? authSelect.value : '',
|
||||
key: keyInput ? keyInput.value : '',
|
||||
pass: passInput ? passInput.value : '',
|
||||
image: imageInput ? imageInput.value : '',
|
||||
});
|
||||
};
|
||||
|
||||
const isDirty = () => snapshot() !== initialSnapshot;
|
||||
|
||||
const openModal = () => {
|
||||
if (!modal) return;
|
||||
modal.classList.add('is-open');
|
||||
modal.setAttribute('aria-hidden', 'false');
|
||||
initialSnapshot = snapshot();
|
||||
};
|
||||
|
||||
const closeModal = (force = false) => {
|
||||
if (!modal) return;
|
||||
if (!force && isDirty()) {
|
||||
const ok = window.confirm('Änderungen nicht gespeichert. Ohne Speichern schließen?');
|
||||
if (!ok) return;
|
||||
}
|
||||
modal.classList.remove('is-open');
|
||||
modal.setAttribute('aria-hidden', 'true');
|
||||
};
|
||||
|
||||
document.querySelectorAll('[data-host-edit]').forEach((btn) => {
|
||||
btn.addEventListener('click', () => {
|
||||
const card = btn.closest('.host-card');
|
||||
if (!card) return;
|
||||
if (idInput) idInput.value = card.dataset.hostId || '';
|
||||
if (nameInput) nameInput.value = card.dataset.name || '';
|
||||
if (hostInput) hostInput.value = card.dataset.host || '';
|
||||
if (portInput) portInput.value = card.dataset.port || '22';
|
||||
if (userInput) userInput.value = card.dataset.username || '';
|
||||
if (authSelect) authSelect.value = card.dataset.auth || 'key';
|
||||
if (keyInput) keyInput.value = card.dataset.keyPath || '';
|
||||
if (passInput) passInput.value = '';
|
||||
if (imageInput) imageInput.value = card.dataset.imageUrl || '';
|
||||
if (submitBtn) submitBtn.textContent = 'Aktualisieren';
|
||||
if (modalTitle) modalTitle.textContent = 'Host bearbeiten';
|
||||
const details = btn.closest('details');
|
||||
if (details) details.removeAttribute('open');
|
||||
openModal();
|
||||
});
|
||||
});
|
||||
|
||||
if (newBtn) {
|
||||
newBtn.addEventListener('click', () => {
|
||||
resetForm();
|
||||
if (modalTitle) modalTitle.textContent = 'Neuer Host';
|
||||
openModal();
|
||||
});
|
||||
}
|
||||
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', () => closeModal(false));
|
||||
}
|
||||
|
||||
if (cancelBtn) {
|
||||
cancelBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
resetForm();
|
||||
});
|
||||
}
|
||||
|
||||
const updateStatus = (card, status) => {
|
||||
const dot = card.querySelector('[data-host-status]');
|
||||
if (!dot) return;
|
||||
dot.classList.remove('status-ok', 'status-auth', 'status-down');
|
||||
if (status === 'ok') dot.classList.add('status-ok');
|
||||
else if (status === 'down') dot.classList.add('status-down');
|
||||
else dot.classList.add('status-auth');
|
||||
};
|
||||
|
||||
const fetchStatus = (card) => {
|
||||
const id = card.dataset.hostId;
|
||||
if (!id) return;
|
||||
fetch(`${window.location.pathname}?status_json=1&id=${encodeURIComponent(id)}`, { cache: 'no-store' })
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data && data.ok) {
|
||||
updateStatus(card, data.status);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
document.querySelectorAll('.host-card').forEach((card) => {
|
||||
fetchStatus(card);
|
||||
});
|
||||
|
||||
const setUpdateUi = (card, data) => {
|
||||
const upd = card.querySelector('[data-update-badge]');
|
||||
const upg = card.querySelector('[data-upgrade-badge]');
|
||||
const time = card.querySelector('[data-update-time]');
|
||||
const updDebug = card.querySelector('[data-update-debug]');
|
||||
const upgDebug = card.querySelector('[data-upgrade-debug]');
|
||||
if (upd) {
|
||||
upd.classList.remove('badge-warn', 'badge-ok', 'badge-error');
|
||||
if (data.updates && data.updates.error) {
|
||||
upd.textContent = 'Updates: Fehler';
|
||||
upd.classList.add('badge-error');
|
||||
upd.setAttribute('title', data.updates.error);
|
||||
} else if (data.updates && typeof data.updates.count === 'number') {
|
||||
upd.textContent = `Updates: ${data.updates.count}`;
|
||||
upd.classList.toggle('badge-warn', data.updates.count > 0);
|
||||
upd.classList.toggle('badge-ok', data.updates.count === 0);
|
||||
if (data.updates.preview || data.updates.raw) {
|
||||
upd.setAttribute('title', data.updates.preview || data.updates.raw);
|
||||
}
|
||||
} else {
|
||||
upd.textContent = 'Updates: –';
|
||||
if (data.updates && (data.updates.preview || data.updates.raw)) {
|
||||
upd.setAttribute('title', data.updates.preview || data.updates.raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (upg) {
|
||||
upg.classList.remove('badge-warn', 'badge-ok', 'badge-error');
|
||||
if (data.os && data.os.error) {
|
||||
upg.textContent = 'OS: Fehler';
|
||||
upg.classList.add('badge-error');
|
||||
upg.setAttribute('title', data.os.error);
|
||||
} else if (data.os && typeof data.os.available === 'boolean') {
|
||||
upg.textContent = data.os.available ? 'OS: Upgrade verfügbar' : 'OS: OK';
|
||||
upg.classList.toggle('badge-warn', data.os.available);
|
||||
upg.classList.toggle('badge-ok', !data.os.available);
|
||||
if (data.os.raw) upg.setAttribute('title', data.os.raw);
|
||||
} else {
|
||||
upg.textContent = 'OS: –';
|
||||
if (data.os && data.os.raw) {
|
||||
upg.setAttribute('title', data.os.raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (updDebug) {
|
||||
const raw = (data.updates && (data.updates.raw || data.updates.preview)) || '';
|
||||
updDebug.textContent = raw ? `Update Debug: ${raw}` : 'Update Debug: –';
|
||||
}
|
||||
if (upgDebug) {
|
||||
const raw = (data.os && data.os.raw) || '';
|
||||
upgDebug.textContent = raw ? `Upgrade Debug: ${raw}` : 'Upgrade Debug: –';
|
||||
}
|
||||
if (time && data.checked_at) {
|
||||
const dt = new Date(data.checked_at);
|
||||
time.textContent = isNaN(dt.getTime()) ? data.checked_at : dt.toLocaleString();
|
||||
}
|
||||
};
|
||||
|
||||
const checkHostUpdates = (card) => {
|
||||
const id = card.dataset.hostId;
|
||||
if (!id) return Promise.resolve();
|
||||
const btn = card.querySelector('[data-host-check]');
|
||||
if (btn) {
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Prüfe...';
|
||||
}
|
||||
return fetch(`${window.location.pathname}?update_json=1&id=${encodeURIComponent(id)}`, { cache: 'no-store' })
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data && data.ok) {
|
||||
setUpdateUi(card, data);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (btn) {
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Updates prüfen';
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
document.querySelectorAll('[data-host-check]').forEach((btn) => {
|
||||
btn.addEventListener('click', () => {
|
||||
const card = btn.closest('.host-card');
|
||||
if (card) checkHostUpdates(card);
|
||||
});
|
||||
});
|
||||
|
||||
if (checkAllBtn) {
|
||||
checkAllBtn.addEventListener('click', async () => {
|
||||
const cards = Array.from(document.querySelectorAll('.host-card'));
|
||||
for (const card of cards) {
|
||||
await checkHostUpdates(card);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const applyStoredUpdate = (card) => {
|
||||
const checkedAt = card.dataset.updateChecked || '';
|
||||
const updateCount = card.dataset.updateCount;
|
||||
const updateError = card.dataset.updateError || '';
|
||||
const upgradeAvailable = card.dataset.upgradeAvailable;
|
||||
const upgradeRaw = card.dataset.upgradeRaw || '';
|
||||
const upgradeError = card.dataset.upgradeError || '';
|
||||
|
||||
const payload = {
|
||||
updates: {},
|
||||
os: {},
|
||||
checked_at: checkedAt || '',
|
||||
};
|
||||
if (updateError) {
|
||||
payload.updates.error = updateError;
|
||||
} else if (updateCount !== undefined && updateCount !== '') {
|
||||
payload.updates.count = Number(updateCount);
|
||||
payload.updates.preview = card.dataset.updatePreview || '';
|
||||
payload.updates.raw = card.dataset.updatePreview || '';
|
||||
} else {
|
||||
payload.updates.preview = card.dataset.updatePreview || '';
|
||||
payload.updates.raw = card.dataset.updatePreview || '';
|
||||
}
|
||||
|
||||
if (upgradeError) {
|
||||
payload.os.error = upgradeError;
|
||||
} else if (upgradeAvailable !== undefined && upgradeAvailable !== '') {
|
||||
payload.os.available = upgradeAvailable === '1' || upgradeAvailable === 'true';
|
||||
payload.os.raw = upgradeRaw;
|
||||
} else {
|
||||
payload.os.raw = upgradeRaw;
|
||||
}
|
||||
|
||||
setUpdateUi(card, payload);
|
||||
};
|
||||
|
||||
const isStale = (checkedAt) => {
|
||||
if (!checkedAt) return true;
|
||||
const dt = new Date(checkedAt);
|
||||
if (isNaN(dt.getTime())) return true;
|
||||
const ageMs = Date.now() - dt.getTime();
|
||||
return ageMs > 24 * 60 * 60 * 1000;
|
||||
};
|
||||
|
||||
document.querySelectorAll('.host-card').forEach((card) => {
|
||||
applyStoredUpdate(card);
|
||||
if (isStale(card.dataset.updateChecked || '')) {
|
||||
checkHostUpdates(card);
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,279 @@
|
||||
.form-card { padding: 14px; }
|
||||
|
||||
.notice-card {
|
||||
padding: 12px 14px;
|
||||
line-height: 1.45;
|
||||
word-break: break-word;
|
||||
}
|
||||
.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;
|
||||
}
|
||||
|
||||
.host-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
.host-card {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 16px;
|
||||
overflow: visible;
|
||||
display: grid;
|
||||
grid-template-rows: 120px 1fr;
|
||||
box-shadow: var(--shadow);
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
.host-card-image {
|
||||
background: linear-gradient(135deg, #2b3a67 0%, #3b2f5c 45%, #1c2b3f 100%);
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
position: relative;
|
||||
border-top-left-radius: 16px;
|
||||
border-top-right-radius: 16px;
|
||||
}
|
||||
.host-card-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(10, 16, 28, 0.35);
|
||||
}
|
||||
.host-card-body {
|
||||
padding: 12px 14px 14px;
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
}
|
||||
.host-card-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
.host-card-title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.status-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 999px;
|
||||
display: inline-block;
|
||||
}
|
||||
.status-ok { background: #31c48d; }
|
||||
.status-auth { background: #fbbf24; }
|
||||
.status-down { background: #ef4444; }
|
||||
|
||||
.host-update-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.update-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel-2);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.badge-ok {
|
||||
border-color: rgba(49,196,141,0.5);
|
||||
background: rgba(49,196,141,0.15);
|
||||
}
|
||||
.badge-warn {
|
||||
border-color: rgba(251,191,36,0.6);
|
||||
background: rgba(251,191,36,0.2);
|
||||
}
|
||||
.badge-error {
|
||||
border-color: rgba(239,68,68,0.6);
|
||||
background: rgba(239,68,68,0.15);
|
||||
}
|
||||
|
||||
.action-menu {
|
||||
position: relative;
|
||||
}
|
||||
.action-menu summary {
|
||||
list-style: none;
|
||||
cursor: pointer;
|
||||
border-radius: 10px;
|
||||
padding: 2px 6px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel-2);
|
||||
}
|
||||
.action-menu summary::-webkit-details-marker { display: none; }
|
||||
.action-menu[open] summary {
|
||||
background: var(--panel);
|
||||
}
|
||||
.action-menu-panel {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: calc(100% + 6px);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
padding: 6px;
|
||||
min-width: 160px;
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
z-index: 200;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.action-menu-panel form { margin: 0; }
|
||||
|
||||
.host-unsaved {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #f3c3b8;
|
||||
background: #fff5f3;
|
||||
color: #7a2114;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.host-debug {
|
||||
margin: 6px 0 0;
|
||||
padding: 6px 8px;
|
||||
background: #0b1020;
|
||||
color: #c7d2fe;
|
||||
border-radius: 8px;
|
||||
font-size: 0.7rem;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
max-height: 120px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.command-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
.command-item {
|
||||
display: grid;
|
||||
grid-template-columns: 28px 1fr auto;
|
||||
gap: 10px;
|
||||
align-items: start;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: var(--panel);
|
||||
}
|
||||
.command-item.is-dragging {
|
||||
opacity: 0.6;
|
||||
}
|
||||
.command-drag {
|
||||
cursor: grab;
|
||||
color: var(--muted);
|
||||
font-size: 1.1rem;
|
||||
padding-top: 4px;
|
||||
}
|
||||
.command-body code {
|
||||
display: inline-block;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.queue-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.queue-badge {
|
||||
display: inline-flex;
|
||||
min-width: 22px;
|
||||
height: 22px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 999px;
|
||||
background: #ff5a3c;
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
font-size: 0.75rem;
|
||||
padding: 0 6px;
|
||||
}
|
||||
|
||||
.modal-card {
|
||||
width: min(1100px, 96vw);
|
||||
}
|
||||
.modal-actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
304
temp/nexus-module-import/modules/pi_control/bootstrap.php
Normal file
304
temp/nexus-module-import/modules/pi_control/bootstrap.php
Normal file
@@ -0,0 +1,304 @@
|
||||
<?php
|
||||
use App\ModuleConfigException;
|
||||
|
||||
$moduleName = 'pi_control';
|
||||
$mm = isset($modules) && $modules instanceof App\ModuleManager ? $modules : modules();
|
||||
|
||||
$mm->registerFunction($moduleName, 'table', function (string $name): string {
|
||||
$prefix = 'picontrol_';
|
||||
$sanitized = preg_replace('/[^a-zA-Z0-9_]/', '', $name);
|
||||
return $prefix . $sanitized;
|
||||
});
|
||||
|
||||
$mm->registerFunction($moduleName, 'pdo', function () use ($moduleName): \PDO {
|
||||
$settings = modules()->settings($moduleName);
|
||||
$useSeparate = !empty($settings['use_separate_db']);
|
||||
|
||||
if ($useSeparate) {
|
||||
// Uses module-specific DB config
|
||||
$module = modules()->get($moduleName);
|
||||
$fallback = $module['db_defaults'] ?? [];
|
||||
return modules()->modulePdo($moduleName, $fallback);
|
||||
}
|
||||
|
||||
$base = app()->basePdo();
|
||||
if (!$base) {
|
||||
throw new ModuleConfigException(
|
||||
$moduleName,
|
||||
'Base-DB ist deaktiviert. Bitte Base-DB aktivieren oder eigene Modul-DB konfigurieren.'
|
||||
);
|
||||
}
|
||||
|
||||
return $base;
|
||||
});
|
||||
|
||||
$mm->registerFunction($moduleName, 'redis', function () use ($moduleName) {
|
||||
$settings = modules()->settings($moduleName);
|
||||
$redis = (array)($settings['redis'] ?? []);
|
||||
$host = (string)($redis['host'] ?? ($settings['redis.host'] ?? getenv('PI_CONTROL_REDIS_HOST') ?: 'redis'));
|
||||
$port = (int)($redis['port'] ?? ($settings['redis.port'] ?? (getenv('PI_CONTROL_REDIS_PORT') !== false ? (int)getenv('PI_CONTROL_REDIS_PORT') : 6379)));
|
||||
$password = (string)($redis['password'] ?? ($settings['redis.password'] ?? getenv('PI_CONTROL_REDIS_PASSWORD') ?: ''));
|
||||
$db = (int)($redis['db'] ?? ($settings['redis.db'] ?? (getenv('PI_CONTROL_REDIS_DB') !== false ? (int)getenv('PI_CONTROL_REDIS_DB') : 0)));
|
||||
|
||||
return new \App\RedisClient($host, $port, $password !== '' ? $password : null, $db);
|
||||
});
|
||||
|
||||
$mm->registerFunction($moduleName, 'ensure_schema', function () use ($moduleName): void {
|
||||
$pdo = module_fn($moduleName, 'pdo');
|
||||
$table = fn(string $name) => module_fn($moduleName, 'table', $name);
|
||||
|
||||
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
|
||||
$hostTable = $table('hosts');
|
||||
$cmdTable = $table('commands');
|
||||
$runTable = $table('runs');
|
||||
$sessionTable = $table('sessions');
|
||||
|
||||
if ($driver === 'pgsql') {
|
||||
$pdo->exec("CREATE TABLE IF NOT EXISTS {$hostTable} (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
host VARCHAR(255) NOT NULL,
|
||||
port INTEGER NOT NULL DEFAULT 22,
|
||||
username VARCHAR(120) NOT NULL,
|
||||
auth_type VARCHAR(20) NOT NULL DEFAULT 'key',
|
||||
key_path TEXT NULL,
|
||||
password TEXT NULL,
|
||||
image_url TEXT NULL,
|
||||
update_checked_at TIMESTAMP NULL,
|
||||
update_count INTEGER NULL,
|
||||
update_preview TEXT NULL,
|
||||
update_error TEXT NULL,
|
||||
upgrade_available BOOLEAN NULL,
|
||||
upgrade_raw TEXT NULL,
|
||||
upgrade_error TEXT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)");
|
||||
$pdo->exec("CREATE TABLE IF NOT EXISTS {$cmdTable} (
|
||||
id SERIAL PRIMARY KEY,
|
||||
label VARCHAR(160) NOT NULL,
|
||||
command TEXT NOT NULL,
|
||||
admin_only BOOLEAN NOT NULL DEFAULT false,
|
||||
timeout_sec INTEGER NULL,
|
||||
sort_order INTEGER NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)");
|
||||
$pdo->exec("CREATE TABLE IF NOT EXISTS {$runTable} (
|
||||
id SERIAL PRIMARY KEY,
|
||||
host_id INTEGER NULL,
|
||||
command_id INTEGER NULL,
|
||||
command_text TEXT NOT NULL,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'pending',
|
||||
output TEXT NULL,
|
||||
error TEXT NULL,
|
||||
exit_code INTEGER NULL,
|
||||
timeout_sec INTEGER NULL,
|
||||
created_by VARCHAR(120) NULL,
|
||||
started_at TIMESTAMP NULL,
|
||||
finished_at TIMESTAMP NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)");
|
||||
$pdo->exec("CREATE TABLE IF NOT EXISTS {$sessionTable} (
|
||||
id SERIAL PRIMARY KEY,
|
||||
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,
|
||||
last_used_at TIMESTAMP NULL
|
||||
)");
|
||||
} else {
|
||||
$pdo->exec("CREATE TABLE IF NOT EXISTS {$hostTable} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(120) NOT NULL,
|
||||
host VARCHAR(255) NOT NULL,
|
||||
port INTEGER NOT NULL DEFAULT 22,
|
||||
username VARCHAR(120) NOT NULL,
|
||||
auth_type VARCHAR(20) NOT NULL DEFAULT 'key',
|
||||
key_path TEXT NULL,
|
||||
password TEXT NULL,
|
||||
image_url TEXT NULL,
|
||||
update_checked_at DATETIME NULL,
|
||||
update_count INTEGER NULL,
|
||||
update_preview TEXT NULL,
|
||||
update_error TEXT NULL,
|
||||
upgrade_available INTEGER NULL,
|
||||
upgrade_raw TEXT NULL,
|
||||
upgrade_error TEXT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)");
|
||||
$pdo->exec("CREATE TABLE IF NOT EXISTS {$cmdTable} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
label VARCHAR(160) NOT NULL,
|
||||
command TEXT NOT NULL,
|
||||
admin_only INTEGER NOT NULL DEFAULT 0,
|
||||
timeout_sec INTEGER NULL,
|
||||
sort_order INTEGER NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)");
|
||||
$pdo->exec("CREATE TABLE IF NOT EXISTS {$runTable} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NULL,
|
||||
command_id INTEGER NULL,
|
||||
command_text TEXT NOT NULL,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'pending',
|
||||
output TEXT NULL,
|
||||
error TEXT NULL,
|
||||
exit_code INTEGER NULL,
|
||||
timeout_sec INTEGER NULL,
|
||||
created_by VARCHAR(120) NULL,
|
||||
started_at DATETIME NULL,
|
||||
finished_at DATETIME NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)");
|
||||
$pdo->exec("CREATE TABLE IF NOT EXISTS {$sessionTable} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
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,
|
||||
last_used_at DATETIME NULL
|
||||
)");
|
||||
}
|
||||
|
||||
// Schema migrations for existing tables
|
||||
if ($driver === 'pgsql') {
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN IF NOT EXISTS image_url TEXT NULL");
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN IF NOT EXISTS update_checked_at TIMESTAMP NULL");
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN IF NOT EXISTS update_count INTEGER NULL");
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN IF NOT EXISTS update_preview TEXT NULL");
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN IF NOT EXISTS update_error TEXT NULL");
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN IF NOT EXISTS upgrade_available BOOLEAN NULL");
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN IF NOT EXISTS upgrade_raw TEXT NULL");
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN IF NOT EXISTS upgrade_error TEXT NULL");
|
||||
$pdo->exec("ALTER TABLE {$cmdTable} ADD COLUMN IF NOT EXISTS timeout_sec INTEGER NULL");
|
||||
$pdo->exec("ALTER TABLE {$cmdTable} ADD COLUMN IF NOT EXISTS sort_order INTEGER NULL");
|
||||
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN IF NOT EXISTS error TEXT NULL");
|
||||
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN IF NOT EXISTS exit_code INTEGER NULL");
|
||||
$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(' . $hostTable . ')');
|
||||
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $col) {
|
||||
$columns[$col['name']] = true;
|
||||
}
|
||||
if (empty($columns['image_url'])) {
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN image_url TEXT NULL");
|
||||
}
|
||||
if (empty($columns['update_checked_at'])) {
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN update_checked_at DATETIME NULL");
|
||||
}
|
||||
if (empty($columns['update_count'])) {
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN update_count INTEGER NULL");
|
||||
}
|
||||
if (empty($columns['update_preview'])) {
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN update_preview TEXT NULL");
|
||||
}
|
||||
if (empty($columns['update_error'])) {
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN update_error TEXT NULL");
|
||||
}
|
||||
if (empty($columns['upgrade_available'])) {
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN upgrade_available INTEGER NULL");
|
||||
}
|
||||
if (empty($columns['upgrade_raw'])) {
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN upgrade_raw TEXT NULL");
|
||||
}
|
||||
if (empty($columns['upgrade_error'])) {
|
||||
$pdo->exec("ALTER TABLE {$hostTable} ADD COLUMN upgrade_error TEXT NULL");
|
||||
}
|
||||
|
||||
$columns = [];
|
||||
$stmt = $pdo->query('PRAGMA table_info(' . $cmdTable . ')');
|
||||
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $col) {
|
||||
$columns[$col['name']] = true;
|
||||
}
|
||||
if (empty($columns['timeout_sec'])) {
|
||||
$pdo->exec("ALTER TABLE {$cmdTable} ADD COLUMN timeout_sec INTEGER NULL");
|
||||
}
|
||||
if (empty($columns['sort_order'])) {
|
||||
$pdo->exec("ALTER TABLE {$cmdTable} ADD COLUMN sort_order INTEGER NULL");
|
||||
}
|
||||
|
||||
$columns = [];
|
||||
$stmt = $pdo->query('PRAGMA table_info(' . $runTable . ')');
|
||||
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $col) {
|
||||
$columns[$col['name']] = true;
|
||||
}
|
||||
if (empty($columns['error'])) {
|
||||
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN error TEXT NULL");
|
||||
}
|
||||
if (empty($columns['exit_code'])) {
|
||||
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN exit_code INTEGER NULL");
|
||||
}
|
||||
if (empty($columns['timeout_sec'])) {
|
||||
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN timeout_sec INTEGER NULL");
|
||||
}
|
||||
if (empty($columns['started_at'])) {
|
||||
$pdo->exec("ALTER TABLE {$runTable} ADD COLUMN started_at DATETIME NULL");
|
||||
}
|
||||
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)
|
||||
$count = (int)$pdo->query('SELECT COUNT(*) FROM ' . $cmdTable)->fetchColumn();
|
||||
if ($count === 0) {
|
||||
$defaults = [
|
||||
['Speicherplatz auf Dateisystem', 'df -T -h', false],
|
||||
['Netzwerkdaten', 'ip -s addr show', false],
|
||||
['CPU-Information', 'cat /proc/cpuinfo', false],
|
||||
['Informationen über USB-Bus', 'lsusb', false],
|
||||
['Uptime', 'uptime -p', false],
|
||||
['Scannen Sie einen I2C-Bus nach Geräten', '/usr/sbin/i2cdetect -y 1', true],
|
||||
['Prozesse (Gib zum Beenden \"q\" ein)', 'top', false],
|
||||
['SSH status', 'systemctl status ssh', false],
|
||||
['Konfigurationsprogramm in Raspberry OS', 'sudo raspi-config', true],
|
||||
['Pinbelegung', 'pinout', false],
|
||||
['Exportiere GPIO (Für Nutzung vorbereiten)', 'echo 22 > /sys/class/gpio/export', true],
|
||||
['Lese GPIO-Wert', 'echo in > /sys/class/gpio/gpio22/direction && cat /sys/class/gpio/gpio22/value', true],
|
||||
['Schreibe \"Low\" GPIO Wert', 'echo out > /sys/class/gpio/gpio22/direction && echo 0 > /sys/class/gpio/gpio22/value', true],
|
||||
['Schreibe \"High\" GPIO Wert', 'echo out > /sys/class/gpio/gpio22/direction && echo 1 > /sys/class/gpio/gpio22/value', true],
|
||||
['Export entfernen (Ressource freigeben)', 'echo 22 > /sys/class/gpio/unexport', true],
|
||||
['Alternative Funktionen von GPIO', 'raspi-gpio funcs', false],
|
||||
['Gerät herunterfahren', 'sudo systemctl poweroff', true],
|
||||
['Gerät neu starten', 'sudo systemctl reboot', true],
|
||||
['Aktualisiere die Betriebssystem-Pakete', 'sudo apt update && sudo apt full-upgrade', true],
|
||||
['Befehle, die zuvor ausgeführt wurden (Quellsprache)', 'history 30', false],
|
||||
['Liste der zuletzt angemeldeten Nutzer', 'last -30 -F', false],
|
||||
['Liste der aktuell angemeldeten Nutzer', 'w', false],
|
||||
['Aktualisierung', 'sudo apt update && sudo apt upgrade -y && sudo apt-get autoremove --purge && sudo apt-get clean && sudo rm -rf /var/lib/apt/lists/* && sudo apt-get update && sudo apt-get remove texlive-*-doc', true],
|
||||
['Update OS', 'sudo apt update && sudo apt full-upgrade -y && sudo apt-get autoremove --purge && sudo apt-get clean && sudo rm -rf /var/lib/apt/lists/* && sudo apt-get update && sudo apt-get remove texlive-*-doc', true],
|
||||
['Paketlisten laden', 'sudo apt-get update; sudo apt-get dist-upgrade -y;exit', true],
|
||||
['Gerät herunterfahren', 'sudo /sbin/shutdown -h now', true],
|
||||
['Gerät neu starten', 'sudo /sbin/reboot', true],
|
||||
];
|
||||
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO ' . $cmdTable . ' (label, command, admin_only) VALUES (:label, :command, :admin_only)'
|
||||
);
|
||||
foreach ($defaults as [$label, $command, $adminOnly]) {
|
||||
$stmt->bindValue(':label', $label, PDO::PARAM_STR);
|
||||
$stmt->bindValue(':command', $command, PDO::PARAM_STR);
|
||||
$stmt->bindValue(':admin_only', (bool)$adminOnly, PDO::PARAM_BOOL);
|
||||
$stmt->execute();
|
||||
}
|
||||
}
|
||||
});
|
||||
14
temp/nexus-module-import/modules/pi_control/design.json
Normal file
14
temp/nexus-module-import/modules/pi_control/design.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"eyebrow": "Modul",
|
||||
"title": "Pi Control",
|
||||
"description": "Verwaltung und Steuerung von Raspberry Pis per SSH, Presets und Konsole.",
|
||||
"actions": [
|
||||
{ "label": "Setup", "href": "/modules/setup/pi_control", "variant": "secondary" }
|
||||
],
|
||||
"tabs": [
|
||||
{ "label": "Ueberblick", "href": "/module/pi_control", "match_prefixes": ["/module/pi_control"] },
|
||||
{ "label": "Hosts", "href": "/module/pi_control/hosts", "match_prefixes": ["/module/pi_control/hosts"] },
|
||||
{ "label": "Befehle", "href": "/module/pi_control/commands", "match_prefixes": ["/module/pi_control/commands"] },
|
||||
{ "label": "Konsole", "href": "/module/pi_control/console", "match_prefixes": ["/module/pi_control/console"] }
|
||||
]
|
||||
}
|
||||
38
temp/nexus-module-import/modules/pi_control/module.json
Normal file
38
temp/nexus-module-import/modules/pi_control/module.json
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"title": "Pi Control",
|
||||
"version": "0.1.0",
|
||||
"description": "Verwaltung und Steuerung von Raspberry Pis (SSH/Commands/Presets).",
|
||||
"setup": {
|
||||
"fields": [
|
||||
{ "name": "use_separate_db", "label": "Eigene Modul-DB nutzen", "type": "checkbox", "required": false, "help": "Wenn aktiv, werden die DB-Daten unten verwendet. Sonst wird die Base-DB genutzt." },
|
||||
{ "name": "db.driver", "label": "DB Driver", "type": "text", "required": false, "help": "z.B. pgsql, mysql, sqlite" },
|
||||
{ "name": "db.host", "label": "DB Host", "type": "text", "required": false },
|
||||
{ "name": "db.port", "label": "DB Port", "type": "number", "required": false },
|
||||
{ "name": "db.dbname", "label": "DB Name", "type": "text", "required": false },
|
||||
{ "name": "db.schema", "label": "DB Schema", "type": "text", "required": false },
|
||||
{ "name": "db.user", "label": "DB User", "type": "text", "required": false },
|
||||
{ "name": "db.password", "label": "DB Passwort", "type": "password", "required": false },
|
||||
{ "name": "ttyd_url", "label": "ttyd URL", "type": "text", "required": false, "help": "z.B. https://staging.nexus.kusche.berlin/ttyd" },
|
||||
{ "name": "terminal_token_ttl", "label": "Token TTL (Minuten)", "type": "number", "required": false, "help": "Gültigkeit der Konsole-Token, z.B. 10" },
|
||||
{ "name": "terminal_shared_secret", "label": "Terminal Shared Secret", "type": "password", "required": false, "help": "Zusätzliche Absicherung für terminal_info (Header X-Terminal-Secret)" },
|
||||
{ "name": "terminal_tmux_session", "label": "tmux Session-Name", "type": "text", "required": false, "help": "Session-Name für bestehende Konsole (Standard: nexus)" },
|
||||
{ "name": "terminal_strict_hostkey", "label": "Strict Host-Key Checking", "type": "checkbox", "required": false, "help": "Aktiviert StrictHostKeyChecking (accept-new) statt Insecure." },
|
||||
{ "name": "exec_default_timeout", "label": "Command-Timeout (Sek.)", "type": "number", "required": false, "help": "Default-Timeout für Befehle, z.B. 300" },
|
||||
{ "name": "settings_reload_sec", "label": "Settings Reload (Sek.)", "type": "number", "required": false, "help": "Wie oft der Worker Settings neu lädt (Standard 30s)" },
|
||||
{ "name": "redis.host", "label": "Redis Host", "type": "text", "required": false, "help": "Service-Name, z.B. redis" },
|
||||
{ "name": "redis.port", "label": "Redis Port", "type": "number", "required": false, "help": "Standard 6379" },
|
||||
{ "name": "redis.password", "label": "Redis Passwort", "type": "password", "required": false },
|
||||
{ "name": "redis.db", "label": "Redis DB", "type": "number", "required": false, "help": "Standard 0" },
|
||||
{ "name": "redis.queue", "label": "Redis Queue", "type": "text", "required": false, "help": "z.B. pi_control:queue" }
|
||||
]
|
||||
},
|
||||
"db_defaults": {
|
||||
"driver": "pgsql",
|
||||
"host": "localhost",
|
||||
"port": 5432,
|
||||
"dbname": "",
|
||||
"schema": "public",
|
||||
"user": "",
|
||||
"password": ""
|
||||
}
|
||||
}
|
||||
32
temp/nexus-module-import/modules/pi_control/pages/asset.php
Normal file
32
temp/nexus-module-import/modules/pi_control/pages/asset.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
$file = (string)($_GET['file'] ?? '');
|
||||
$base = realpath(__DIR__ . '/../assets');
|
||||
$map = [
|
||||
'pi_control.css' => $base . '/pi_control.css',
|
||||
'console.js' => $base . '/console.js',
|
||||
'hosts.js' => $base . '/hosts.js',
|
||||
'commands.js' => $base . '/commands.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;
|
||||
181
temp/nexus-module-import/modules/pi_control/pages/commands.php
Normal file
181
temp/nexus-module-import/modules/pi_control/pages/commands.php
Normal file
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
$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');
|
||||
$assets->addScript('/module/pi_control/asset?file=commands.js', 'footer', true);
|
||||
}
|
||||
|
||||
$notice = null;
|
||||
$error = null;
|
||||
|
||||
if (isset($_GET['reorder_json'])) {
|
||||
require_admin();
|
||||
$payload = json_decode(file_get_contents('php://input'), true);
|
||||
$order = is_array($payload['order'] ?? null) ? $payload['order'] : [];
|
||||
if ($order) {
|
||||
$stmt = $pdo->prepare('UPDATE ' . $table('commands') . ' SET sort_order = :sort_order WHERE id = :id');
|
||||
$pos = 1;
|
||||
foreach ($order as $id) {
|
||||
$stmt->execute([
|
||||
'sort_order' => $pos++,
|
||||
'id' => (int)$id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode(['ok' => true]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
require_admin();
|
||||
$deleteId = (int)($_POST['delete_id'] ?? 0);
|
||||
$editId = (int)($_POST['id'] ?? 0);
|
||||
$label = trim((string)($_POST['label'] ?? ''));
|
||||
$command = trim((string)($_POST['command'] ?? ''));
|
||||
$adminOnly = !empty($_POST['admin_only']) ? 1 : 0;
|
||||
$timeoutSec = (int)($_POST['timeout_sec'] ?? 0);
|
||||
|
||||
if ($deleteId > 0) {
|
||||
$stmt = $pdo->prepare('DELETE FROM ' . $table('commands') . ' WHERE id = :id');
|
||||
$stmt->execute(['id' => $deleteId]);
|
||||
$notice = 'Befehl gelöscht.';
|
||||
} else {
|
||||
if ($label === '' || $command === '') {
|
||||
$error = 'Bitte Label und Command angeben.';
|
||||
} else {
|
||||
if ($editId > 0) {
|
||||
$stmt = $pdo->prepare(
|
||||
'UPDATE ' . $table('commands') . ' SET label = :label, command = :command, admin_only = :admin_only, timeout_sec = :timeout_sec WHERE id = :id'
|
||||
);
|
||||
$stmt->execute([
|
||||
'id' => $editId,
|
||||
'label' => $label,
|
||||
'command' => $command,
|
||||
'admin_only' => $adminOnly,
|
||||
'timeout_sec' => $timeoutSec > 0 ? $timeoutSec : null,
|
||||
]);
|
||||
$notice = 'Befehl aktualisiert.';
|
||||
} else {
|
||||
$nextSort = (int)$pdo->query('SELECT COALESCE(MAX(sort_order), 0) + 1 FROM ' . $table('commands'))->fetchColumn();
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO ' . $table('commands') . ' (label, command, admin_only, timeout_sec, sort_order) VALUES (:label, :command, :admin_only, :timeout_sec, :sort_order)'
|
||||
);
|
||||
$stmt->execute([
|
||||
'label' => $label,
|
||||
'command' => $command,
|
||||
'admin_only' => $adminOnly,
|
||||
'timeout_sec' => $timeoutSec > 0 ? $timeoutSec : null,
|
||||
'sort_order' => $nextSort,
|
||||
]);
|
||||
$notice = 'Befehl gespeichert.';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$commands = $pdo->query('SELECT * FROM ' . $table('commands') . ' ORDER BY COALESCE(sort_order, id) ASC, id ASC')->fetchAll(PDO::FETCH_ASSOC);
|
||||
?>
|
||||
<?= module_shell_header('pi_control', [
|
||||
'title' => 'Befehle',
|
||||
]) ?>
|
||||
<div class="module-flow">
|
||||
<section class="module-box">
|
||||
<div class="module-box-head">
|
||||
<div>
|
||||
<h2 class="module-box-title">Befehle</h2>
|
||||
<p>Verwalte vordefinierte SSH-Befehle.</p>
|
||||
</div>
|
||||
<button class="module-button module-button--primary" type="button" data-command-new>+ Neuer Befehl</button>
|
||||
</div>
|
||||
|
||||
<?php if ($error): ?>
|
||||
<div class="setup-db-message setup-db-message--error" style="margin-top:16px;">
|
||||
<?= e($error) ?>
|
||||
</div>
|
||||
<?php elseif ($notice): ?>
|
||||
<div class="setup-db-message setup-db-message--success" style="margin-top:16px;">
|
||||
<?= e($notice) ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="module-box" style="margin-top:16px;">
|
||||
<strong>Vorhandene Befehle</strong>
|
||||
<?php if (!$commands): ?>
|
||||
<div class="muted" style="margin-top:.75rem;">Keine Befehle vorhanden.</div>
|
||||
<?php else: ?>
|
||||
<ul class="command-list" data-command-list style="margin-top:.75rem;">
|
||||
<?php foreach ($commands as $c): ?>
|
||||
<li class="command-item" draggable="true"
|
||||
data-command-id="<?= e((string)$c['id']) ?>"
|
||||
data-label="<?= e((string)($c['label'] ?? '')) ?>"
|
||||
data-command="<?= e((string)($c['command'] ?? '')) ?>"
|
||||
data-timeout="<?= e((string)($c['timeout_sec'] ?? '')) ?>"
|
||||
data-admin="<?= !empty($c['admin_only']) ? '1' : '0' ?>">
|
||||
<div class="command-drag">⋮⋮</div>
|
||||
<div class="command-body">
|
||||
<div class="command-title">
|
||||
<strong><?= e($c['label'] ?? '') ?></strong>
|
||||
<?php if (!empty($c['admin_only'])): ?>
|
||||
<span class="pill">Admin</span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div class="muted" style="margin-top:4px;">
|
||||
<code><?= e($c['command'] ?? '') ?></code>
|
||||
</div>
|
||||
<div class="muted" style="margin-top:4px;">
|
||||
Timeout: <?= !empty($c['timeout_sec']) ? e((string)$c['timeout_sec']) . 's' : 'default' ?>
|
||||
</div>
|
||||
</div>
|
||||
<details class="action-menu">
|
||||
<summary>☰</summary>
|
||||
<div class="action-menu-panel">
|
||||
<button class="nav-link" type="button" data-command-edit>Bearbeiten</button>
|
||||
<form method="post" onsubmit="return confirm('Befehl wirklich löschen?')">
|
||||
<input type="hidden" name="delete_id" value="<?= e((string)$c['id']) ?>">
|
||||
<button class="nav-link" type="submit">Löschen</button>
|
||||
</form>
|
||||
</div>
|
||||
</details>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<p class="muted" style="margin-top:.5rem;">Reihenfolge per Drag & Drop ändern.</p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="modal" data-command-modal aria-hidden="true">
|
||||
<div class="modal-card">
|
||||
<div class="modal-header">
|
||||
<strong data-command-modal-title>Neuer Befehl</strong>
|
||||
<button class="icon-button" type="button" data-command-close>×</button>
|
||||
</div>
|
||||
<form method="post" class="form-grid" style="margin-top:.75rem;" data-command-form>
|
||||
<input type="hidden" name="id" value="">
|
||||
<input type="text" name="label" placeholder="Label" required>
|
||||
<textarea name="command" rows="4" placeholder="Command" required></textarea>
|
||||
<input type="number" name="timeout_sec" placeholder="Timeout (Sek., optional)">
|
||||
<label class="muted" style="display:flex; gap:8px; align-items:center;">
|
||||
<input type="checkbox" name="admin_only" value="1">
|
||||
Nur Admin
|
||||
</label>
|
||||
<div class="host-unsaved" data-command-unsaved style="display:none;">
|
||||
<span class="muted">Änderungen nicht gespeichert.</span>
|
||||
<div style="display:flex; gap:10px; flex-wrap:wrap;">
|
||||
<button class="cta-button" type="submit" data-command-submit>Speichern</button>
|
||||
<button class="nav-link" type="button" data-command-discard>Änderungen verwerfen</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex; gap:10px; flex-wrap:wrap;">
|
||||
<button class="cta-button" type="submit" data-command-submit>Speichern</button>
|
||||
<button class="nav-link" type="button" data-command-cancel>Zurücksetzen</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<?= module_shell_footer() ?>
|
||||
527
temp/nexus-module-import/modules/pi_control/pages/console.php
Normal file
527
temp/nexus-module-import/modules/pi_control/pages/console.php
Normal file
@@ -0,0 +1,527 @@
|
||||
<?php
|
||||
$pdo = module_fn('pi_control', 'pdo');
|
||||
module_fn('pi_control', 'ensure_schema');
|
||||
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
|
||||
|
||||
$notice = null;
|
||||
$error = null;
|
||||
$terminalNotice = null;
|
||||
$terminalError = null;
|
||||
$terminalUrl = null;
|
||||
$terminalToken = null;
|
||||
$terminalHostLabel = null;
|
||||
|
||||
$settings = modules()->settings('pi_control');
|
||||
$assets = app()->assets();
|
||||
if ($assets) {
|
||||
$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';
|
||||
$defaultTimeout = (int)($settings['exec_default_timeout'] ?? (getenv('PI_CONTROL_EXEC_DEFAULT_TIMEOUT') !== false ? (int)getenv('PI_CONTROL_EXEC_DEFAULT_TIMEOUT') : 300));
|
||||
$defaultTimeout = $defaultTimeout > 0 ? $defaultTimeout : 300;
|
||||
$queueName = (string)($settings['redis']['queue'] ?? ($settings['redis.queue'] ?? (getenv('PI_CONTROL_REDIS_QUEUE') ?: 'pi_control:queue')));
|
||||
$tokenTtl = (int)($settings['terminal_token_ttl'] ?? 10);
|
||||
$tokenTtl = $tokenTtl > 0 ? $tokenTtl : 10;
|
||||
|
||||
$hosts = $pdo->query('SELECT * FROM ' . $table('hosts') . ' ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC);
|
||||
$commands = $pdo->query('SELECT * FROM ' . $table('commands') . ' ORDER BY COALESCE(sort_order, id) ASC, id ASC')->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$renderRuns = function (array $runs): string {
|
||||
ob_start();
|
||||
if (!$runs) {
|
||||
echo '<tr><td colspan="8" class="muted">Noch keine Runs.</td></tr>';
|
||||
return ob_get_clean();
|
||||
}
|
||||
foreach ($runs as $r) {
|
||||
$out = (string)($r['output'] ?? '');
|
||||
$err = (string)($r['error'] ?? '');
|
||||
$snippet = $out !== '' ? $out : $err;
|
||||
if (strlen($snippet) > 140) {
|
||||
$snippet = substr($snippet, 0, 140) . '…';
|
||||
}
|
||||
echo '<tr>';
|
||||
echo '<td>' . e((string)$r['id']) . '</td>';
|
||||
echo '<td>' . e((string)($r['status'] ?? '')) . '</td>';
|
||||
echo '<td>' . e((string)($r['host_name'] ?? $r['host_addr'] ?? '')) . '</td>';
|
||||
echo '<td class="muted" style="max-width:360px;"><code>' . e((string)($r['command_text'] ?? '')) . '</code></td>';
|
||||
echo '<td>' . e((string)($r['created_by'] ?? '')) . '</td>';
|
||||
echo '<td class="muted" style="max-width:240px;"><code>' . e($snippet) . '</code></td>';
|
||||
echo '<td>' . (!empty($r['timeout_sec']) ? e((string)$r['timeout_sec']) . 's' : 'default') . '</td>';
|
||||
$status = (string)($r['status'] ?? '');
|
||||
echo '<td>';
|
||||
if ($status === 'queued') {
|
||||
echo '<button class="nav-link" type="button" data-queue-action="cancel" data-run-id="' . e((string)$r['id']) . '">Stoppen</button>';
|
||||
echo '<button class="nav-link" type="button" data-queue-action="delete" data-run-id="' . e((string)$r['id']) . '">Löschen</button>';
|
||||
} elseif ($status === 'running') {
|
||||
echo '<span class="muted">läuft</span>';
|
||||
} else {
|
||||
echo '<button class="nav-link" type="button" data-queue-action="delete" data-run-id="' . e((string)$r['id']) . '">Löschen</button>';
|
||||
}
|
||||
echo '</td>';
|
||||
echo '</tr>';
|
||||
}
|
||||
return ob_get_clean();
|
||||
};
|
||||
|
||||
if (isset($_GET['queue_json'])) {
|
||||
$runs = $pdo->query(
|
||||
'SELECT r.*, h.name AS host_name, h.host AS host_addr
|
||||
FROM ' . $table('runs') . ' r
|
||||
LEFT JOIN ' . $table('hosts') . ' h ON h.id = r.host_id
|
||||
ORDER BY r.id DESC LIMIT 20'
|
||||
)->fetchAll(PDO::FETCH_ASSOC);
|
||||
$count = (int)$pdo->query(
|
||||
"SELECT COUNT(*) FROM " . $table('runs') . " WHERE status IN ('queued','running','cancel_requested')"
|
||||
)->fetchColumn();
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode([
|
||||
'ok' => true,
|
||||
'next' => 10,
|
||||
'count' => $count,
|
||||
'html' => $renderRuns($runs),
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (isset($_GET['queue_action_json'])) {
|
||||
$runId = (int)($_POST['run_id'] ?? 0);
|
||||
$action = (string)($_POST['action'] ?? '');
|
||||
$error = null;
|
||||
|
||||
if ($runId <= 0 || !in_array($action, ['cancel', 'delete'], true)) {
|
||||
$error = 'Ungültige Anfrage.';
|
||||
} else {
|
||||
$stmt = $pdo->prepare('SELECT * FROM ' . $table('runs') . ' WHERE id = :id LIMIT 1');
|
||||
$stmt->execute(['id' => $runId]);
|
||||
$run = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
if (!$run) {
|
||||
$error = 'Run nicht gefunden.';
|
||||
} else {
|
||||
$status = (string)($run['status'] ?? '');
|
||||
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
$nowExpr = $driver === 'pgsql' ? 'NOW()' : "DATETIME('now')";
|
||||
|
||||
if ($action === 'cancel') {
|
||||
if ($status !== 'queued') {
|
||||
$error = 'Nur queued Runs können gestoppt werden.';
|
||||
} else {
|
||||
$pdo->exec('UPDATE ' . $table('runs') . ' SET status = \'canceled\', finished_at = ' . $nowExpr . ' WHERE id = ' . (int)$runId);
|
||||
try {
|
||||
$redis = module_fn('pi_control', 'redis');
|
||||
$payload = json_encode(['run_id' => $runId]);
|
||||
$redis->command(['LREM', $queueName, '0', $payload]);
|
||||
} catch (\Throwable $e) {
|
||||
// ignore redis cleanup errors
|
||||
}
|
||||
}
|
||||
} elseif ($action === 'delete') {
|
||||
if ($status === 'running') {
|
||||
$error = 'Laufende Runs können nicht gelöscht werden.';
|
||||
} else {
|
||||
$pdo->prepare('DELETE FROM ' . $table('runs') . ' WHERE id = :id')->execute(['id' => $runId]);
|
||||
try {
|
||||
$redis = module_fn('pi_control', 'redis');
|
||||
$payload = json_encode(['run_id' => $runId]);
|
||||
$redis->command(['LREM', $queueName, '0', $payload]);
|
||||
} catch (\Throwable $e) {
|
||||
// ignore redis cleanup errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode([
|
||||
'ok' => $error === null,
|
||||
'error' => $error,
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (isset($_GET['open_console_json'])) {
|
||||
$hostId = (int)($_POST['terminal_host_id'] ?? 0);
|
||||
$presetId = (int)($_POST['terminal_preset_id'] ?? 0);
|
||||
$rawCommand = trim((string)($_POST['terminal_command_text'] ?? ''));
|
||||
$terminalError = null;
|
||||
$terminalUrl = null;
|
||||
$terminalToken = null;
|
||||
$terminalHostLabel = null;
|
||||
|
||||
if ($hostId <= 0) {
|
||||
$terminalError = 'Bitte einen Host wählen.';
|
||||
} elseif ($ttydUrl === '') {
|
||||
$terminalError = 'ttyd URL fehlt. Bitte im Setup setzen.';
|
||||
} else {
|
||||
$presetCommand = '';
|
||||
if ($presetId > 0) {
|
||||
foreach ($commands as $c) {
|
||||
if ((int)$c['id'] === $presetId) {
|
||||
if (!auth_is_admin() && !empty($c['admin_only'])) {
|
||||
$terminalError = 'Diese Vorlage ist nur für Admins.';
|
||||
} else {
|
||||
$presetCommand = (string)$c['command'];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!$terminalError) {
|
||||
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
$expiresSql = $driver === 'pgsql'
|
||||
? "NOW() + INTERVAL '{$tokenTtl} minutes'"
|
||||
: "DATETIME('now', '+{$tokenTtl} minutes')";
|
||||
|
||||
$token = bin2hex(random_bytes(24));
|
||||
$terminalToken = $token;
|
||||
$stmt = $pdo->prepare(
|
||||
'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);
|
||||
foreach ($hosts as $h) {
|
||||
if ((int)$h['id'] === $hostId) {
|
||||
$terminalHostLabel = (string)($h['name'] ?? $h['host']);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode([
|
||||
'ok' => $terminalError === null,
|
||||
'error' => $terminalError,
|
||||
'url' => $terminalUrl,
|
||||
'token' => $terminalToken,
|
||||
'host' => $terminalHostLabel,
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (isset($_GET['run_command_json'])) {
|
||||
$hostId = (int)($_POST['terminal_host_id'] ?? 0);
|
||||
$commandId = (int)($_POST['terminal_preset_id'] ?? 0);
|
||||
$rawCommand = trim((string)($_POST['terminal_command_text'] ?? ''));
|
||||
$timeoutSec = $defaultTimeout;
|
||||
$error = null;
|
||||
$notice = null;
|
||||
|
||||
if ($hostId <= 0) {
|
||||
$error = 'Bitte einen Host wählen.';
|
||||
} elseif ($commandId <= 0 && $rawCommand === '') {
|
||||
$error = 'Bitte einen Befehl wählen oder einen Befehl eingeben.';
|
||||
} else {
|
||||
$selectedCommand = '';
|
||||
if ($commandId > 0) {
|
||||
foreach ($commands as $c) {
|
||||
if ((int)$c['id'] === $commandId) {
|
||||
if (!auth_is_admin() && !empty($c['admin_only'])) {
|
||||
$error = 'Dieser Befehl ist nur für Admins.';
|
||||
} else {
|
||||
$selectedCommand = (string)$c['command'];
|
||||
if (!empty($c['timeout_sec'])) {
|
||||
$timeoutSec = (int)$c['timeout_sec'];
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$error) {
|
||||
$commandText = $selectedCommand !== '' ? $selectedCommand : $rawCommand;
|
||||
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
if ($driver === 'pgsql') {
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO ' . $table('runs') . ' (host_id, command_id, command_text, status, timeout_sec, created_by)
|
||||
VALUES (:host_id, :command_id, :command_text, :status, :timeout_sec, :created_by)
|
||||
RETURNING id'
|
||||
);
|
||||
$stmt->execute([
|
||||
'host_id' => $hostId,
|
||||
'command_id' => $commandId > 0 ? $commandId : null,
|
||||
'command_text' => $commandText,
|
||||
'status' => 'queued',
|
||||
'timeout_sec' => $timeoutSec,
|
||||
'created_by' => auth_display_name() ?: null,
|
||||
]);
|
||||
$runId = (int)$stmt->fetchColumn();
|
||||
} else {
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO ' . $table('runs') . ' (host_id, command_id, command_text, status, timeout_sec, created_by)
|
||||
VALUES (:host_id, :command_id, :command_text, :status, :timeout_sec, :created_by)'
|
||||
);
|
||||
$stmt->execute([
|
||||
'host_id' => $hostId,
|
||||
'command_id' => $commandId > 0 ? $commandId : null,
|
||||
'command_text' => $commandText,
|
||||
'status' => 'queued',
|
||||
'timeout_sec' => $timeoutSec,
|
||||
'created_by' => auth_display_name() ?: null,
|
||||
]);
|
||||
$runId = (int)$pdo->lastInsertId();
|
||||
}
|
||||
try {
|
||||
$redis = module_fn('pi_control', 'redis');
|
||||
$payload = json_encode(['run_id' => $runId], JSON_THROW_ON_ERROR);
|
||||
$redis->command(['RPUSH', $queueName, $payload]);
|
||||
$notice = 'Befehl wurde in die Queue gestellt.';
|
||||
} catch (\Throwable $e) {
|
||||
$pdo->exec('UPDATE ' . $table('runs') . ' SET status = \'queue_error\' WHERE id = ' . (int)$runId);
|
||||
$notice = 'Befehl gespeichert, aber Queue nicht erreichbar.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode([
|
||||
'ok' => $error === null,
|
||||
'error' => $error,
|
||||
'notice' => $notice,
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (isset($_GET['send_active_json'])) {
|
||||
$hostId = (int)($_POST['terminal_host_id'] ?? 0);
|
||||
$commandId = (int)($_POST['terminal_preset_id'] ?? 0);
|
||||
$rawCommand = trim((string)($_POST['terminal_command_text'] ?? ''));
|
||||
$error = null;
|
||||
$notice = null;
|
||||
|
||||
if ($hostId <= 0) {
|
||||
$error = 'Bitte einen Host wählen.';
|
||||
} elseif ($commandId <= 0 && $rawCommand === '') {
|
||||
$error = 'Bitte einen Befehl wählen oder einen Befehl eingeben.';
|
||||
} else {
|
||||
$selectedCommand = '';
|
||||
if ($commandId > 0) {
|
||||
foreach ($commands as $c) {
|
||||
if ((int)$c['id'] === $commandId) {
|
||||
if (!auth_is_admin() && !empty($c['admin_only'])) {
|
||||
$error = 'Dieser Befehl ist nur für Admins.';
|
||||
} else {
|
||||
$selectedCommand = (string)$c['command'];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!$error) {
|
||||
$commandText = $selectedCommand !== '' ? $selectedCommand : $rawCommand;
|
||||
$stmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
|
||||
$stmt->execute(['id' => $hostId]);
|
||||
$host = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
if (!$host) {
|
||||
$error = 'Host nicht gefunden.';
|
||||
} else {
|
||||
$settings = modules()->settings('pi_control');
|
||||
$strictHostKey = !empty($settings['terminal_strict_hostkey']) || getenv('PI_CONTROL_STRICT_HOSTKEY') === '1';
|
||||
[$ok, $sendError] = sendToActiveConsole($host, $commandText, $strictHostKey);
|
||||
if ($ok) {
|
||||
$notice = 'Befehl wurde in der bestehenden Konsole ausgeführt.';
|
||||
} else {
|
||||
$error = $sendError ?: 'Bestehende Konsole nicht verfügbar.';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode([
|
||||
'ok' => $error === null,
|
||||
'error' => $error,
|
||||
'notice' => $notice,
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Form submits are handled via AJAX to avoid reloads.
|
||||
|
||||
$runs = $pdo->query(
|
||||
'SELECT r.*, h.name AS host_name, h.host AS host_addr
|
||||
FROM ' . $table('runs') . ' r
|
||||
LEFT JOIN ' . $table('hosts') . ' h ON h.id = r.host_id
|
||||
ORDER BY r.id DESC LIMIT 20'
|
||||
)->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
function sendToActiveConsole(array $host, string $command, bool $strictHostKey): array
|
||||
{
|
||||
$hostAddr = (string)($host['host'] ?? '');
|
||||
$user = (string)($host['username'] ?? '');
|
||||
$port = (int)($host['port'] ?? 22);
|
||||
$authType = (string)($host['auth_type'] ?? 'key');
|
||||
$keyPath = (string)($host['key_path'] ?? '');
|
||||
$password = (string)($host['password'] ?? '');
|
||||
|
||||
if ($hostAddr === '' || $user === '') {
|
||||
return [false, 'Hostdaten unvollständig.'];
|
||||
}
|
||||
|
||||
$opts = $strictHostKey
|
||||
? '-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/root/.ssh/known_hosts'
|
||||
: '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null';
|
||||
|
||||
$target = escapeshellarg($user . '@' . $hostAddr);
|
||||
$cmdB64 = base64_encode($command);
|
||||
$remote = 'CMD_B64="$0"; CMD="$(printf "%s" "$CMD_B64" | base64 -d)"; ' .
|
||||
'command -v tmux >/dev/null 2>&1 || exit 2; ' .
|
||||
'tmux has-session -t nexus 2>/dev/null || exit 3; ' .
|
||||
'tmux send-keys -t nexus "$CMD" C-m';
|
||||
|
||||
$cmd = 'ssh ' . $opts . ' -p ' . (int)$port . ' ';
|
||||
if ($authType === 'key' && $keyPath !== '') {
|
||||
$cmd .= '-i ' . escapeshellarg($keyPath) . ' ';
|
||||
}
|
||||
$cmd .= $target . ' -- /bin/bash -lc ' . escapeshellarg($remote) . ' ' . escapeshellarg($cmdB64);
|
||||
if ($authType === 'pass' && $password !== '') {
|
||||
$cmd = 'sshpass -p ' . escapeshellarg($password) . ' ' . $cmd;
|
||||
}
|
||||
|
||||
$descriptors = [
|
||||
1 => ['pipe', 'w'],
|
||||
2 => ['pipe', 'w'],
|
||||
];
|
||||
$process = proc_open($cmd, $descriptors, $pipes);
|
||||
if (!is_resource($process)) {
|
||||
return [false, 'proc_open failed'];
|
||||
}
|
||||
$out = stream_get_contents($pipes[1]);
|
||||
$err = stream_get_contents($pipes[2]);
|
||||
$status = proc_get_status($process);
|
||||
$exitCode = (int)($status['exitcode'] ?? 1);
|
||||
proc_close($process);
|
||||
|
||||
if ($exitCode === 0) {
|
||||
return [true, null];
|
||||
}
|
||||
if ($exitCode === 2) {
|
||||
return [false, 'tmux ist auf dem Host nicht installiert.'];
|
||||
}
|
||||
if ($exitCode === 3) {
|
||||
return [false, 'Keine aktive Konsole gefunden.'];
|
||||
}
|
||||
$msg = trim($err !== '' ? $err : $out);
|
||||
return [false, $msg !== '' ? $msg : 'Befehl konnte nicht gesendet werden.'];
|
||||
}
|
||||
?>
|
||||
<?= module_shell_header('pi_control', [
|
||||
'title' => 'Konsole',
|
||||
]) ?>
|
||||
<div class="module-flow">
|
||||
<section class="module-box">
|
||||
<div class="module-box-head">
|
||||
<div>
|
||||
<h2 class="module-box-title">Konsole</h2>
|
||||
<p>Wähle einen Host und führe einen Befehl aus.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($error): ?>
|
||||
<div class="setup-db-message setup-db-message--error" style="margin-top:16px;">
|
||||
<?= e($error) ?>
|
||||
</div>
|
||||
<?php elseif ($notice): ?>
|
||||
<div class="setup-db-message setup-db-message--success" style="margin-top:16px;">
|
||||
<?= e($notice) ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="module-box" style="margin-top:16px;">
|
||||
<strong>Live-Konsole</strong>
|
||||
<div class="setup-db-message setup-db-message--error" style="margin-top:1rem; display:none;" data-console-error></div>
|
||||
<div class="setup-db-message setup-db-message--success" style="margin-top:1rem; display:none;" data-console-notice></div>
|
||||
<form method="post" class="form-grid" style="margin-top:.75rem;" data-console-form>
|
||||
<label class="form-field">
|
||||
<span class="muted">Host</span>
|
||||
<select name="terminal_host_id" required title="Pi auswählen, zu dem die Konsole verbindet.">
|
||||
<option value="">Host wählen</option>
|
||||
<?php foreach ($hosts as $h): ?>
|
||||
<option value="<?= e((string)$h['id']) ?>"><?= e($h['name'] ?? $h['host']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span class="muted">Vorlage</span>
|
||||
<select name="terminal_preset_id" title="Optional: Vorlage direkt in der Konsole ausführen.">
|
||||
<option value="">Vorlage auswählen (optional)</option>
|
||||
<?php foreach ($commands as $c): ?>
|
||||
<?php if (!auth_is_admin() && !empty($c['admin_only'])) { continue; } ?>
|
||||
<option value="<?= e((string)$c['id']) ?>" data-command="<?= e((string)($c['command'] ?? '')) ?>">
|
||||
<?= e($c['label'] ?? '') ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span class="muted">Direkter Befehl</span>
|
||||
<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>Neue Konsole öffnen</button>
|
||||
<button class="nav-link" type="button" data-run-command>Im Hintergrund ausführen</button>
|
||||
<button class="icon-button queue-button" type="button" data-queue-button>
|
||||
Queue
|
||||
<span class="queue-badge" data-queue-count>0</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<div class="muted" style="margin-top:.5rem;">
|
||||
Token: <code data-console-token></code>
|
||||
</div>
|
||||
|
||||
<?php if ($terminalUrl): ?>
|
||||
<div class="console-launch"
|
||||
data-url="<?= e($terminalUrl) ?>"
|
||||
data-host="<?= e($terminalHostLabel ?: 'Konsole') ?>"
|
||||
data-token="<?= e($terminalToken ?: '') ?>"></div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="modal" data-queue-modal aria-hidden="true">
|
||||
<div class="modal-card">
|
||||
<div class="modal-header">
|
||||
<strong>Queue</strong>
|
||||
<div class="modal-actions">
|
||||
<span class="muted">Update in <span data-queue-countdown>10</span>s</span>
|
||||
<button class="icon-button" type="button" data-queue-refresh title="Jetzt aktualisieren">↻</button>
|
||||
<button class="icon-button" type="button" data-queue-close title="Schließen">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-top:.75rem; overflow:auto;">
|
||||
<table class="table" style="min-width:720px;">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Status</th>
|
||||
<th>Host</th>
|
||||
<th>Command</th>
|
||||
<th>Von</th>
|
||||
<th>Output</th>
|
||||
<th>Timeout</th>
|
||||
<th>Aktion</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-queue-body>
|
||||
<?= $renderRuns($runs) ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<?= module_shell_footer() ?>
|
||||
479
temp/nexus-module-import/modules/pi_control/pages/hosts.php
Normal file
479
temp/nexus-module-import/modules/pi_control/pages/hosts.php
Normal file
@@ -0,0 +1,479 @@
|
||||
<?php
|
||||
$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');
|
||||
$assets->addScript('/module/pi_control/asset?file=hosts.js', 'footer', true);
|
||||
}
|
||||
|
||||
$notice = null;
|
||||
$error = null;
|
||||
|
||||
if (isset($_GET['status_json'])) {
|
||||
require_admin();
|
||||
$id = (int)($_GET['id'] ?? 0);
|
||||
$stmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
|
||||
$stmt->execute(['id' => $id]);
|
||||
$host = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
if (!$host) {
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode(['ok' => false, 'error' => 'not_found']);
|
||||
exit;
|
||||
}
|
||||
$settings = modules()->settings('pi_control');
|
||||
$strictHostKey = !empty($settings['terminal_strict_hostkey']);
|
||||
$reachable = hostReachable((string)($host['host'] ?? ''), (int)($host['port'] ?? 22));
|
||||
$authOk = $reachable ? hostAuthOk($host, $strictHostKey) : false;
|
||||
$status = !$reachable ? 'down' : ($authOk ? 'ok' : 'auth');
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode(['ok' => true, 'status' => $status]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (isset($_GET['update_json'])) {
|
||||
require_admin();
|
||||
$id = (int)($_GET['id'] ?? 0);
|
||||
$stmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
|
||||
$stmt->execute(['id' => $id]);
|
||||
$host = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
if (!$host) {
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode(['ok' => false, 'error' => 'not_found']);
|
||||
exit;
|
||||
}
|
||||
$settings = modules()->settings('pi_control');
|
||||
$strictHostKey = !empty($settings['terminal_strict_hostkey']);
|
||||
|
||||
$updateCmd = <<<'SH'
|
||||
if ! command -v apt-get >/dev/null 2>&1; then echo "__ERR__NO_APT"; exit 2; fi;
|
||||
if sudo -n apt update -qq >/dev/null 2>&1; then echo "__APT_UPDATE__=1"; else echo "__APT_UPDATE__=0"; fi;
|
||||
count=$(apt-get -s dist-upgrade 2>/dev/null | grep -c "^Inst ");
|
||||
echo "__COUNT__=$count"
|
||||
SH;
|
||||
$upgradeCmd = <<<'SH'
|
||||
id="$(. /etc/os-release 2>/dev/null && echo "${ID:-}")";
|
||||
current="$(. /etc/os-release 2>/dev/null && echo "${VERSION_CODENAME:-}")";
|
||||
if [ "$id" != "debian" ] || [ -z "$current" ]; then echo "__UPGRADE__=0"; exit 0; fi;
|
||||
latest="$( (command -v curl >/dev/null 2>&1 && curl -fsSL https://deb.debian.org/debian/dists/stable/Release) || (command -v wget >/dev/null 2>&1 && wget -qO- https://deb.debian.org/debian/dists/stable/Release) )";
|
||||
latest="$(printf "%s" "$latest" | awk -F": " "/^Codename:/{print $2}")";
|
||||
if [ -z "$latest" ]; then echo "__UPGRADE__=0"; echo "__RAW__=NO_FETCH"; exit 0; fi;
|
||||
if [ "$current" != "$latest" ]; then echo "__UPGRADE__=1"; else echo "__UPGRADE__=0"; fi
|
||||
SH;
|
||||
|
||||
[$updExit, $updOut, $updErr] = runSshCommandCapture($host, $updateCmd, $strictHostKey, 20);
|
||||
$updOutStr = (string)$updOut;
|
||||
$updErrStr = (string)$updErr;
|
||||
$updateCount = null;
|
||||
$updatePreview = '';
|
||||
$updateErr = str_contains($updOutStr, '__ERR__NO_APT');
|
||||
if (preg_match('/^__COUNT__=(\d+)$/m', $updOutStr, $m)) {
|
||||
$updateCount = (int)$m[1];
|
||||
}
|
||||
$updatePreview = trim($updOutStr);
|
||||
if (strlen($updatePreview) > 1200) {
|
||||
$updatePreview = substr($updatePreview, 0, 1200);
|
||||
}
|
||||
|
||||
[$upgExit, $upgOut, $upgErr] = runSshCommandCapture($host, $upgradeCmd, $strictHostKey, 25);
|
||||
$upgOutStr = (string)$upgOut;
|
||||
$upgErrStr = (string)$upgErr;
|
||||
$upgradeAvailable = null;
|
||||
$upgradeErr = str_contains($upgOutStr, '__ERR__');
|
||||
if ($upgExit === 0 && !$upgradeErr) {
|
||||
if (preg_match('/^__UPGRADE__=(0|1)$/m', $upgOutStr, $m)) {
|
||||
$upgradeAvailable = $m[1] === '1';
|
||||
}
|
||||
}
|
||||
|
||||
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
$nowExpr = $driver === 'pgsql' ? 'NOW()' : "DATETIME('now')";
|
||||
$updCountVal = $updateCount;
|
||||
$updErrVal = (!$updateErr && $updateCount !== null) ? null : trim($updErrStr ?: $updOutStr);
|
||||
$upgAvailVal = $upgradeAvailable;
|
||||
$upgErrVal = $upgExit === 0 && !$upgradeErr ? null : trim($upgErrStr ?: $upgOutStr);
|
||||
$stmt = $pdo->prepare(
|
||||
'UPDATE ' . $table('hosts') . ' SET update_checked_at = ' . $nowExpr . ',
|
||||
update_count = :update_count,
|
||||
update_preview = :update_preview,
|
||||
update_error = :update_error,
|
||||
upgrade_available = :upgrade_available,
|
||||
upgrade_raw = :upgrade_raw,
|
||||
upgrade_error = :upgrade_error
|
||||
WHERE id = :id'
|
||||
);
|
||||
$stmt->execute([
|
||||
'update_count' => $updCountVal,
|
||||
'update_preview' => $updatePreview !== '' ? $updatePreview : null,
|
||||
'update_error' => $updErrVal,
|
||||
'upgrade_available' => $upgAvailVal === null ? null : ($upgAvailVal ? 1 : 0),
|
||||
'upgrade_raw' => $upgExit === 0 ? trim($upgOutStr) : null,
|
||||
'upgrade_error' => $upgErrVal,
|
||||
'id' => $id,
|
||||
]);
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode([
|
||||
'ok' => true,
|
||||
'updates' => [
|
||||
'count' => $updateCount,
|
||||
'preview' => $updatePreview,
|
||||
'raw' => $updatePreview,
|
||||
'error' => (!$updateErr && $updateCount !== null) ? '' : trim($updErrStr ?: $updOutStr),
|
||||
],
|
||||
'os' => [
|
||||
'available' => $upgradeAvailable,
|
||||
'raw' => $upgExit === 0 ? trim($upgOutStr) : '',
|
||||
'error' => $upgExit === 0 && !$upgradeErr ? '' : trim($upgErrStr ?: $upgOutStr),
|
||||
],
|
||||
'checked_at' => date('c'),
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
require_admin();
|
||||
$deleteId = (int)($_POST['delete_id'] ?? 0);
|
||||
$editId = (int)($_POST['id'] ?? 0);
|
||||
$name = trim((string)($_POST['name'] ?? ''));
|
||||
$host = trim((string)($_POST['host'] ?? ''));
|
||||
$port = (int)($_POST['port'] ?? 22);
|
||||
$username = trim((string)($_POST['username'] ?? ''));
|
||||
$authType = trim((string)($_POST['auth_type'] ?? 'key'));
|
||||
$keyPath = trim((string)($_POST['key_path'] ?? ''));
|
||||
$password = trim((string)($_POST['password'] ?? ''));
|
||||
$imageUrl = trim((string)($_POST['image_url'] ?? ''));
|
||||
|
||||
if ($deleteId > 0) {
|
||||
$stmt = $pdo->prepare('DELETE FROM ' . $table('hosts') . ' WHERE id = :id');
|
||||
$stmt->execute(['id' => $deleteId]);
|
||||
$notice = 'Host gelöscht.';
|
||||
} else {
|
||||
if ($name === '' || $host === '' || $username === '') {
|
||||
$error = 'Bitte Name, Host und Benutzer angeben.';
|
||||
} else {
|
||||
if ($editId > 0) {
|
||||
$stmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
|
||||
$stmt->execute(['id' => $editId]);
|
||||
$existing = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
|
||||
$passwordToStore = $password !== '' ? $password : ($existing['password'] ?? null);
|
||||
$stmt = $pdo->prepare(
|
||||
'UPDATE ' . $table('hosts') . ' SET name = :name, host = :host, port = :port, username = :username, auth_type = :auth_type, key_path = :key_path, password = :password, image_url = :image_url WHERE id = :id'
|
||||
);
|
||||
$stmt->execute([
|
||||
'id' => $editId,
|
||||
'name' => $name,
|
||||
'host' => $host,
|
||||
'port' => $port > 0 ? $port : 22,
|
||||
'username' => $username,
|
||||
'auth_type' => $authType !== '' ? $authType : 'key',
|
||||
'key_path' => $keyPath !== '' ? $keyPath : null,
|
||||
'password' => $passwordToStore,
|
||||
'image_url' => $imageUrl !== '' ? $imageUrl : null,
|
||||
]);
|
||||
$notice = 'Host aktualisiert.';
|
||||
} else {
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO ' . $table('hosts') . ' (name, host, port, username, auth_type, key_path, password, image_url) VALUES (:name, :host, :port, :username, :auth_type, :key_path, :password, :image_url)'
|
||||
);
|
||||
$stmt->execute([
|
||||
'name' => $name,
|
||||
'host' => $host,
|
||||
'port' => $port > 0 ? $port : 22,
|
||||
'username' => $username,
|
||||
'auth_type' => $authType !== '' ? $authType : 'key',
|
||||
'key_path' => $keyPath !== '' ? $keyPath : null,
|
||||
'password' => $password !== '' ? $password : null,
|
||||
'image_url' => $imageUrl !== '' ? $imageUrl : null,
|
||||
]);
|
||||
$notice = 'Host gespeichert.';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$hosts = $pdo->query('SELECT * FROM ' . $table('hosts') . ' ORDER BY id DESC')->fetchAll(PDO::FETCH_ASSOC);
|
||||
$settings = modules()->settings('pi_control');
|
||||
$strictHostKey = !empty($settings['terminal_strict_hostkey']);
|
||||
|
||||
function hostReachable(string $host, int $port): bool
|
||||
{
|
||||
$errno = 0;
|
||||
$errstr = '';
|
||||
$fp = @fsockopen($host, $port, $errno, $errstr, 1.2);
|
||||
if ($fp) {
|
||||
fclose($fp);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function runSshCommand(string $cmd, int $timeoutSec): int
|
||||
{
|
||||
$descriptors = [
|
||||
1 => ['pipe', 'w'],
|
||||
2 => ['pipe', 'w'],
|
||||
];
|
||||
$process = proc_open($cmd, $descriptors, $pipes);
|
||||
if (!is_resource($process)) {
|
||||
return 255;
|
||||
}
|
||||
stream_set_blocking($pipes[1], false);
|
||||
stream_set_blocking($pipes[2], false);
|
||||
$start = time();
|
||||
while (true) {
|
||||
$status = proc_get_status($process);
|
||||
if (!$status['running']) {
|
||||
$code = (int)$status['exitcode'];
|
||||
proc_close($process);
|
||||
return $code;
|
||||
}
|
||||
if (time() - $start > $timeoutSec) {
|
||||
proc_terminate($process, 9);
|
||||
proc_close($process);
|
||||
return 124;
|
||||
}
|
||||
usleep(100000);
|
||||
}
|
||||
}
|
||||
|
||||
function runSshCommandCapture(array $host, string $command, bool $strictHostKey, int $timeoutSec): array
|
||||
{
|
||||
$hostAddr = (string)($host['host'] ?? '');
|
||||
$user = (string)($host['username'] ?? '');
|
||||
$port = (int)($host['port'] ?? 22);
|
||||
$authType = (string)($host['auth_type'] ?? 'key');
|
||||
$keyPath = (string)($host['key_path'] ?? '');
|
||||
$password = (string)($host['password'] ?? '');
|
||||
|
||||
$opts = $strictHostKey
|
||||
? '-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/root/.ssh/known_hosts'
|
||||
: '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null';
|
||||
$opts .= ' -o ConnectTimeout=6 -o NumberOfPasswordPrompts=1 -o LogLevel=ERROR -o RequestTTY=no';
|
||||
|
||||
$target = escapeshellarg($user . '@' . $hostAddr);
|
||||
$remote = '/bin/sh -c ' . escapeshellarg($command);
|
||||
$cmd = 'ssh -T ' . $opts . ' -p ' . (int)$port . ' ';
|
||||
if ($authType === 'key' && $keyPath !== '') {
|
||||
$cmd .= '-i ' . escapeshellarg($keyPath) . ' -o BatchMode=yes ';
|
||||
} elseif ($authType === 'key') {
|
||||
$cmd .= '-o BatchMode=yes ';
|
||||
}
|
||||
$cmd .= $target . ' -- ' . $remote;
|
||||
if ($authType === 'pass' && $password !== '') {
|
||||
$cmd = 'sshpass -p ' . escapeshellarg($password) . ' ' . $cmd;
|
||||
}
|
||||
|
||||
$descriptors = [
|
||||
1 => ['pipe', 'w'],
|
||||
2 => ['pipe', 'w'],
|
||||
];
|
||||
$process = proc_open($cmd, $descriptors, $pipes);
|
||||
if (!is_resource($process)) {
|
||||
return [255, '', 'proc_open failed'];
|
||||
}
|
||||
stream_set_blocking($pipes[1], false);
|
||||
stream_set_blocking($pipes[2], false);
|
||||
$out = '';
|
||||
$err = '';
|
||||
$start = time();
|
||||
while (true) {
|
||||
$status = proc_get_status($process);
|
||||
$out .= stream_get_contents($pipes[1]);
|
||||
$err .= stream_get_contents($pipes[2]);
|
||||
if (!$status['running']) {
|
||||
$exit = (int)$status['exitcode'];
|
||||
proc_close($process);
|
||||
return [$exit, $out, $err];
|
||||
}
|
||||
if (time() - $start > $timeoutSec) {
|
||||
proc_terminate($process, 9);
|
||||
proc_close($process);
|
||||
return [124, $out, $err];
|
||||
}
|
||||
usleep(100000);
|
||||
}
|
||||
}
|
||||
|
||||
function hostAuthOk(array $host, bool $strictHostKey): bool
|
||||
{
|
||||
$hostAddr = (string)($host['host'] ?? '');
|
||||
$user = (string)($host['username'] ?? '');
|
||||
$port = (int)($host['port'] ?? 22);
|
||||
$authType = (string)($host['auth_type'] ?? 'key');
|
||||
$keyPath = (string)($host['key_path'] ?? '');
|
||||
$password = (string)($host['password'] ?? '');
|
||||
if ($hostAddr === '' || $user === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$opts = $strictHostKey
|
||||
? '-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/root/.ssh/known_hosts'
|
||||
: '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null';
|
||||
$opts .= ' -o ConnectTimeout=2 -o NumberOfPasswordPrompts=1';
|
||||
|
||||
$target = escapeshellarg($user . '@' . $hostAddr);
|
||||
$cmd = 'ssh ' . $opts . ' -p ' . (int)$port . ' ';
|
||||
if ($authType === 'key' && $keyPath !== '') {
|
||||
$cmd .= '-i ' . escapeshellarg($keyPath) . ' -o BatchMode=yes ';
|
||||
} elseif ($authType === 'key') {
|
||||
$cmd .= '-o BatchMode=yes ';
|
||||
}
|
||||
$cmd .= $target . ' -- true';
|
||||
|
||||
if ($authType === 'pass') {
|
||||
if ($password === '') {
|
||||
return false;
|
||||
}
|
||||
$cmd = 'sshpass -p ' . escapeshellarg($password) . ' ' . $cmd;
|
||||
}
|
||||
|
||||
$exitCode = runSshCommand($cmd, 3);
|
||||
return $exitCode === 0;
|
||||
}
|
||||
?>
|
||||
<?= module_shell_header('pi_control', [
|
||||
'title' => 'Hosts',
|
||||
]) ?>
|
||||
<div class="module-flow">
|
||||
<section class="module-box">
|
||||
<div class="module-box-head">
|
||||
<div>
|
||||
<h2 class="module-box-title">Hosts</h2>
|
||||
<p>Verwalte die Raspberry Pis, die du steuern möchtest.</p>
|
||||
</div>
|
||||
<div style="display:flex; gap:10px; flex-wrap:wrap;">
|
||||
<button class="module-button module-button--secondary module-button--small" type="button" data-host-check-all>Alle Hosts prüfen</button>
|
||||
<button class="module-button module-button--primary" type="button" data-host-new>+ Neuer Host</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($error): ?>
|
||||
<div class="setup-db-message setup-db-message--error" style="margin-top:16px;">
|
||||
<?= e($error) ?>
|
||||
</div>
|
||||
<?php elseif ($notice): ?>
|
||||
<div class="setup-db-message setup-db-message--success" style="margin-top:16px;">
|
||||
<?= e($notice) ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="module-box-grid module-box-grid--panels" style="margin-top:16px;">
|
||||
<div class="module-box form-card">
|
||||
<strong>Registrierte Hosts</strong>
|
||||
<?php if (!$hosts): ?>
|
||||
<div class="muted" style="margin-top:.75rem;">Keine Hosts vorhanden.</div>
|
||||
<?php else: ?>
|
||||
<div class="host-grid" style="margin-top:.75rem;">
|
||||
<?php foreach ($hosts as $h): ?>
|
||||
<div class="host-card"
|
||||
data-host-id="<?= e((string)$h['id']) ?>"
|
||||
data-name="<?= e((string)($h['name'] ?? '')) ?>"
|
||||
data-host="<?= e((string)($h['host'] ?? '')) ?>"
|
||||
data-port="<?= e((string)($h['port'] ?? 22)) ?>"
|
||||
data-username="<?= e((string)($h['username'] ?? '')) ?>"
|
||||
data-auth="<?= e((string)($h['auth_type'] ?? 'key')) ?>"
|
||||
data-key-path="<?= e((string)($h['key_path'] ?? '')) ?>"
|
||||
data-image-url="<?= e((string)($h['image_url'] ?? '')) ?>"
|
||||
data-update-checked="<?= e((string)($h['update_checked_at'] ?? '')) ?>"
|
||||
data-update-count="<?= e((string)($h['update_count'] ?? '')) ?>"
|
||||
data-update-error="<?= e((string)($h['update_error'] ?? '')) ?>"
|
||||
data-update-preview="<?= e((string)($h['update_preview'] ?? '')) ?>"
|
||||
data-upgrade-available="<?= e((string)($h['upgrade_available'] ?? '')) ?>"
|
||||
data-upgrade-raw="<?= e((string)($h['upgrade_raw'] ?? '')) ?>"
|
||||
data-upgrade-error="<?= e((string)($h['upgrade_error'] ?? '')) ?>">
|
||||
<div class="host-card-image"<?= !empty($h['image_url']) ? ' style="background-image:url(' . e((string)$h['image_url']) . ')"' : '' ?>>
|
||||
<div class="host-card-overlay"></div>
|
||||
</div>
|
||||
<div class="host-card-body">
|
||||
<div class="host-card-header">
|
||||
<div class="host-card-title">
|
||||
<span class="status-dot status-auth" data-host-status></span>
|
||||
<strong><?= e((string)($h['name'] ?? '')) ?></strong>
|
||||
</div>
|
||||
<details class="action-menu">
|
||||
<summary>☰</summary>
|
||||
<div class="action-menu-panel">
|
||||
<button class="nav-link" type="button" data-host-edit>Bearbeiten</button>
|
||||
<form method="post" onsubmit="return confirm('Host wirklich löschen?')">
|
||||
<input type="hidden" name="delete_id" value="<?= e((string)$h['id']) ?>">
|
||||
<button class="nav-link" type="submit">Löschen</button>
|
||||
</form>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<div class="muted"><?= e((string)($h['host'] ?? '')) ?>:<?= e((string)($h['port'] ?? 22)) ?></div>
|
||||
<div class="muted"><?= e((string)($h['username'] ?? '')) ?> · <?= e((string)($h['auth_type'] ?? '')) ?></div>
|
||||
<div class="host-update-row">
|
||||
<span class="update-badge" data-update-badge>Updates: –</span>
|
||||
<span class="update-badge" data-upgrade-badge>OS: –</span>
|
||||
<span class="muted" data-update-time>Nie geprüft</span>
|
||||
</div>
|
||||
<pre class="host-debug" data-update-debug>Update Debug: –</pre>
|
||||
<pre class="host-debug" data-upgrade-debug>Upgrade Debug: –</pre>
|
||||
<div style="display:flex; gap:8px; flex-wrap:wrap;">
|
||||
<button class="nav-link" type="button" data-host-check>Updates prüfen</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="modal" data-host-modal aria-hidden="true">
|
||||
<div class="modal-card">
|
||||
<div class="modal-header">
|
||||
<strong data-host-modal-title>Neuer Host</strong>
|
||||
<button class="icon-button" type="button" data-host-close>×</button>
|
||||
</div>
|
||||
<form method="post" class="form-grid" style="margin-top:.75rem;" data-host-form>
|
||||
<input type="hidden" name="id" value="">
|
||||
<label class="form-field">
|
||||
<span class="muted">Name</span>
|
||||
<input type="text" name="name" placeholder="z.B. Wohnzimmer-Pi" required title="Eindeutiger Anzeigename für diesen Pi.">
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span class="muted">Host / IP</span>
|
||||
<input type="text" name="host" placeholder="z.B. 192.168.178.14 oder pi.local" required title="Hostname oder IP im Heimnetzwerk.">
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span class="muted">SSH Port</span>
|
||||
<input type="number" name="port" placeholder="22" value="22" title="Standard ist 22.">
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span class="muted">SSH Benutzer</span>
|
||||
<input type="text" name="username" placeholder="z.B. pi" required title="Benutzername auf dem Pi.">
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span class="muted">Auth-Typ</span>
|
||||
<select name="auth_type" title="key = SSH-Key, password = Passwort">
|
||||
<option value="key">key (SSH-Key)</option>
|
||||
<option value="pass">pass (Passwort)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span class="muted">Key-Pfad (optional)</span>
|
||||
<input type="text" name="key_path" placeholder="/home/app/.ssh/id_rsa" title="Pfad zum Private-Key im Webserver-Container.">
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span class="muted">Passwort (optional)</span>
|
||||
<input type="password" name="password" placeholder="SSH-Passwort" title="Nur nutzen, wenn Auth-Typ = pass.">
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span class="muted">Bild-URL (optional)</span>
|
||||
<input type="text" name="image_url" placeholder="https://..." title="Optionales Bild für die Host-Karte.">
|
||||
</label>
|
||||
<div style="display:flex; gap:10px; flex-wrap:wrap;">
|
||||
<button class="cta-button" type="submit" data-host-submit>Speichern</button>
|
||||
<button class="nav-link" type="button" data-host-cancel>Zurücksetzen</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<?= module_shell_footer() ?>
|
||||
41
temp/nexus-module-import/modules/pi_control/pages/index.php
Normal file
41
temp/nexus-module-import/modules/pi_control/pages/index.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
$pdo = module_fn('pi_control', 'pdo');
|
||||
module_fn('pi_control', 'ensure_schema');
|
||||
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
|
||||
|
||||
$hostCount = (int)$pdo->query('SELECT COUNT(*) FROM ' . $table('hosts'))->fetchColumn();
|
||||
$cmdCount = (int)$pdo->query('SELECT COUNT(*) FROM ' . $table('commands'))->fetchColumn();
|
||||
$runCount = (int)$pdo->query('SELECT COUNT(*) FROM ' . $table('runs'))->fetchColumn();
|
||||
?>
|
||||
<?= module_shell_header('pi_control', [
|
||||
'title' => 'Raspberry Pi Steuerung',
|
||||
]) ?>
|
||||
<div class="module-flow">
|
||||
<section class="module-box">
|
||||
<div class="module-box-head">
|
||||
<div>
|
||||
<h2 class="module-box-title">Raspberry Pi Steuerung</h2>
|
||||
<p>SSH Hosts verwalten, Befehle definieren und Aktionen ausführen.</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="module-box-grid module-box-grid--stats">
|
||||
<div class="module-box-soft">
|
||||
<strong>Hosts</strong>
|
||||
<div class="muted" style="margin-top:.35rem;">Registriert: <?= e((string)$hostCount) ?></div>
|
||||
<div style="margin-top:.75rem;"><a class="module-button module-button--secondary module-button--small" href="/module/pi_control/hosts">Hosts verwalten</a></div>
|
||||
</div>
|
||||
<div class="module-box-soft">
|
||||
<strong>Befehle</strong>
|
||||
<div class="muted" style="margin-top:.35rem;">Presets: <?= e((string)$cmdCount) ?></div>
|
||||
<div style="margin-top:.75rem;"><a class="module-button module-button--secondary module-button--small" href="/module/pi_control/commands">Befehle verwalten</a></div>
|
||||
</div>
|
||||
<div class="module-box-soft">
|
||||
<strong>Konsole</strong>
|
||||
<div class="muted" style="margin-top:.35rem;">Runs: <?= e((string)$runCount) ?></div>
|
||||
<div style="margin-top:.75rem;"><a class="module-button module-button--secondary module-button--small" href="/module/pi_control/console">Konsole öffnen</a></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?= module_shell_footer() ?>
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
$pdo = module_fn('pi_control', 'pdo');
|
||||
module_fn('pi_control', 'ensure_schema');
|
||||
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
$settings = modules()->settings('pi_control');
|
||||
$sharedSecret = trim((string)($settings['terminal_shared_secret'] ?? ''));
|
||||
if ($sharedSecret !== '') {
|
||||
$provided = trim((string)($_SERVER['HTTP_X_TERMINAL_SECRET'] ?? ''));
|
||||
if (!hash_equals($sharedSecret, $provided)) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['ok' => false, 'error' => 'unauthorized']);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
$token = '';
|
||||
if (!empty($_GET['token'])) {
|
||||
$token = trim((string)$_GET['token']);
|
||||
} elseif (!empty($_SERVER['HTTP_X_TERMINAL_TOKEN'])) {
|
||||
$token = trim((string)$_SERVER['HTTP_X_TERMINAL_TOKEN']);
|
||||
}
|
||||
|
||||
if ($token === '') {
|
||||
http_response_code(400);
|
||||
echo json_encode(['ok' => false, 'error' => 'missing_token']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
$nowSql = $driver === 'pgsql' ? 'NOW()' : "DATETIME('now')";
|
||||
|
||||
$sessionStmt = $pdo->prepare(
|
||||
'SELECT * FROM ' . $table('sessions') . ' WHERE token = :token AND expires_at > ' . $nowSql . ' LIMIT 1'
|
||||
);
|
||||
$sessionStmt->execute(['token' => $token]);
|
||||
$session = $sessionStmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$session) {
|
||||
http_response_code(404);
|
||||
echo json_encode(['ok' => false, 'error' => 'invalid_or_expired']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$hostStmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
|
||||
$hostStmt->execute(['id' => (int)$session['host_id']]);
|
||||
$host = $hostStmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$host) {
|
||||
http_response_code(404);
|
||||
echo json_encode(['ok' => false, 'error' => 'host_not_found']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$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' => [
|
||||
'name' => (string)($host['name'] ?? ''),
|
||||
'host' => (string)($host['host'] ?? ''),
|
||||
'port' => (int)($host['port'] ?? 22),
|
||||
'username' => (string)($host['username'] ?? ''),
|
||||
'auth_type' => (string)($host['auth_type'] ?? 'key'),
|
||||
'key_path' => (string)($host['key_path'] ?? ''),
|
||||
'password' => (string)($host['password'] ?? ''),
|
||||
],
|
||||
'command' => $commandText,
|
||||
'strict_hostkey' => !empty($settings['terminal_strict_hostkey']),
|
||||
'tmux_session' => (string)($settings['terminal_tmux_session'] ?? ''),
|
||||
]);
|
||||
exit;
|
||||
Reference in New Issue
Block a user