109 lines
5.5 KiB
JavaScript
109 lines
5.5 KiB
JavaScript
// window.api für die Web-Version: gleiche Schnittstelle wie src/preload.js (Electron),
|
||
// aber über einen WebSocket zum MrTerm-Web-Server. Dateidialoge, Zwischenablage und Links laufen im Browser.
|
||
(() => {
|
||
'use strict';
|
||
const listeners = new Map();
|
||
const waits = new Map();
|
||
let ws, seq = 0, queue = [], retry = 0, banner;
|
||
const emit = (ch, args) => listeners.get(ch)?.forEach((fn) => { try { fn(...args); } catch (e) { console.error(e); } });
|
||
|
||
function showBanner(text) {
|
||
if (!document.body) return;
|
||
if (!banner) {
|
||
banner = document.createElement('div');
|
||
banner.style.cssText = 'position:fixed;left:50%;top:10px;transform:translateX(-50%);z-index:9999;background:var(--card,#222);color:var(--text,#eee);border:1px solid var(--border,#444);border-radius:10px;padding:8px 14px;font:13px system-ui;box-shadow:0 6px 24px #0006';
|
||
document.body.append(banner);
|
||
}
|
||
banner.textContent = text;
|
||
banner.hidden = !text;
|
||
}
|
||
|
||
function connect() {
|
||
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`);
|
||
ws.onopen = () => { retry = 0; showBanner(''); for (const m of queue) ws.send(m); queue = []; };
|
||
ws.onmessage = (e) => {
|
||
const m = JSON.parse(e.data);
|
||
if (m.t === 'reply') {
|
||
const w = waits.get(m.id);
|
||
if (!w) return;
|
||
waits.delete(m.id);
|
||
m.ok ? w.resolve(m.v) : w.reject(new Error(m.v));
|
||
} else if (m.t === 'evt') emit(m.ch, m.args || []);
|
||
};
|
||
ws.onclose = (e) => {
|
||
for (const w of waits.values()) w.reject(new Error('Connection to the MrTerm server lost.'));
|
||
waits.clear();
|
||
if (e.code === 4001) { location.href = '/'; return; }
|
||
// Sitzung abgelaufen? Dann zur Anmeldung, sonst neu verbinden
|
||
fetch('/api/me', { headers: { 'X-MrTerm': '1' } }).then((r) => {
|
||
if (r.status === 401) { location.href = '/'; return; }
|
||
showBanner(window.I18N ? I18N.t('Connection lost – reconnecting …') : 'Connection lost – reconnecting …');
|
||
setTimeout(connect, Math.min(1000 * 2 ** retry++, 15000));
|
||
}).catch(() => { showBanner(window.I18N ? I18N.t('Connection lost – reconnecting …') : 'Connection lost – reconnecting …'); setTimeout(connect, Math.min(1000 * 2 ** retry++, 15000)); });
|
||
};
|
||
}
|
||
const post = (m) => { const s = JSON.stringify(m); if (ws.readyState === 1) ws.send(s); else queue.push(s); };
|
||
const remote = (ch, args) => new Promise((resolve, reject) => { const id = ++seq; waits.set(id, { resolve, reject }); post({ t: 'call', id, ch, args }); });
|
||
|
||
// Datei im Browser auswählen und als Text lesen
|
||
function pickFile(accept) {
|
||
return new Promise((resolve) => {
|
||
const inp = document.createElement('input');
|
||
inp.type = 'file';
|
||
if (accept) inp.accept = accept;
|
||
inp.style.display = 'none';
|
||
inp.onchange = async () => { const f = inp.files[0]; inp.remove(); resolve(f ? { name: f.name, content: await f.text() } : null); };
|
||
inp.addEventListener('cancel', () => { inp.remove(); resolve(null); });
|
||
document.body.append(inp);
|
||
inp.click();
|
||
});
|
||
}
|
||
function downloadText(name, text) {
|
||
const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
|
||
const a = Object.assign(document.createElement('a'), { href: url, download: name });
|
||
document.body.append(a); a.click(); a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||
}
|
||
|
||
// Kanäle, die im Browser selbst erledigt werden
|
||
const local = {
|
||
// Ohne HTTPS gibt es navigator.clipboard nicht: Kopieren per execCommand, Einfügen dann nur per Strg+V
|
||
'clipboard:write': (t) => {
|
||
if (navigator.clipboard && window.isSecureContext) return navigator.clipboard.writeText(String(t));
|
||
const ta = Object.assign(document.createElement('textarea'), { value: String(t) });
|
||
ta.style.cssText = 'position:fixed;opacity:0';
|
||
document.body.append(ta); ta.select(); document.execCommand('copy'); ta.remove();
|
||
},
|
||
'clipboard:read': () => {
|
||
if (navigator.clipboard && window.isSecureContext) return navigator.clipboard.readText();
|
||
throw new Error('Pasting from the menu needs HTTPS. Use Ctrl+Shift+V or Ctrl+V instead.');
|
||
},
|
||
'shell:open': (url) => { if (/^https?:\/\//i.test(url)) window.open(url, '_blank', 'noopener'); },
|
||
'backup:saveFile': (content, name) => { downloadText(name, content); return name; },
|
||
'key:pickFile': async () => { const f = await pickFile(); return f ? { name: f.name, content: f.content, publicKey: '' } : null; },
|
||
'import:pickFile': async () => pickFile(),
|
||
'vault:importSshConfig': () => { throw new Error('Not available in the web version.'); },
|
||
};
|
||
|
||
window.api = {
|
||
platform: 'web',
|
||
call: (ch, ...args) => (local[ch] ? Promise.resolve().then(() => local[ch](...args)) : remote(ch, args)),
|
||
on(ch, fn) {
|
||
if (!listeners.has(ch)) listeners.set(ch, new Set());
|
||
listeners.get(ch).add(fn);
|
||
return () => listeners.get(ch).delete(fn);
|
||
},
|
||
win: { min() {}, max() {}, close() {} },
|
||
ssh: {
|
||
write: (id, d) => post({ t: 'send', ch: 'ssh:write', args: [id, d] }),
|
||
resize: (id, c, r) => post({ t: 'send', ch: 'ssh:resize', args: [id, c, r] }),
|
||
close: (id) => post({ t: 'send', ch: 'ssh:close', args: [id] }),
|
||
},
|
||
rdp: { bounds() {}, show() {}, hide() {}, focus() {}, close() {} },
|
||
replySecret: (reqId, v) => post({ t: 'send', ch: 'secret:reply', args: [reqId, v] }),
|
||
pairReply: (reqId, ok) => post({ t: 'send', ch: 'sync:pairReply', args: [reqId, ok] }),
|
||
};
|
||
document.documentElement.classList.add('web');
|
||
connect();
|
||
})();
|