diff --git a/Core/Api/ExtensionEndpoints.cs b/Core/Api/ExtensionEndpoints.cs new file mode 100644 index 0000000..a967057 --- /dev/null +++ b/Core/Api/ExtensionEndpoints.cs @@ -0,0 +1,97 @@ +using Microsoft.AspNetCore.StaticFiles; +using OpenStreamMS.Services.Extensions; + +namespace OpenStreamMS.Core.Api; + +public record ExtensionInstallRequest(string Token, string Sha256, bool Replace = false); +public record ExtensionEnableRequest(bool Enabled); +public record CatalogAddRequest(string Url); +public record ExtensionLogResponse(string[] Lines); + +public static class ExtensionEndpoints +{ + public static IEndpointRouteBuilder MapExtensionApi(this IEndpointRouteBuilder app) + { + var g = app.MapGroup("/api/extensions").WithTags("Extensions"); + + g.MapGet("", (ExtensionManager m) => TypedResults.Ok(m.GetAll())) + .WithSummary("Extensiones instaladas y operación en curso"); + + g.MapGet("/operation/log", (ExtensionManager m) => TypedResults.Ok(new ExtensionLogResponse(m.GetOperationLog()))) + .WithSummary("Salida de la última instalación o desinstalación"); + + g.MapPost("/preview", (PreviewRequest req, ExtensionManager m, CancellationToken ct) => + Guard(async () => Results.Ok(await m.PreviewAsync(req, ct)))) + .WithSummary("Descargar y comprobar una extensión sin instalarla") + .WithDescription(""" + Acepta un enlace de GitHub (owner/repo, …/tree/ref/carpeta, …/releases/tag/x) o una + entrada de catálogo. Devuelve lo que hace, la versión, el commit y el SHA-256 del + paquete, y un token para instalar exactamente eso. + """); + + g.MapPost("/install", (ExtensionInstallRequest req, ExtensionManager m) => + Guard(() => { m.StartInstall(req.Token, req.Sha256, req.Replace); return Task.FromResult(Results.Accepted("/api/extensions")); })) + .WithSummary("Instalar lo previsualizado (el SHA-256 debe coincidir)"); + + g.MapPost("/{id}/uninstall", (string id, ExtensionManager m) => + Guard(() => { m.StartUninstall(id); return Task.FromResult(Results.Accepted("/api/extensions")); })) + .WithSummary("Desinstalar una extensión"); + + g.MapPost("/{id}/enabled", (string id, ExtensionEnableRequest req, ExtensionManager m) => + Guard(() => { m.SetEnabled(id, req.Enabled); return Task.FromResult(Results.NoContent()); })) + .WithSummary("Activar o desactivar ganchos, apps y pestaña (el componente sigue instalado)"); + + g.MapPost("/{id}/detect", (string id, ExtensionManager m) => + Guard(() => Task.FromResult(Results.Ok(new { installed = m.Recheck(id) })))) + .WithSummary("Volver a comprobar si el componente está instalado"); + + g.MapGet("/{id}/update", (string id, ExtensionManager m, CancellationToken ct) => + Guard(async () => Results.Ok(await m.CheckUpdateAsync(id, ct)))) + .WithSummary("Buscar una versión nueva (devuelve la vista previa si la hay)"); + + g.MapGet("/{id}/log", (string id, ExtensionManager m) => TypedResults.Ok(new ExtensionLogResponse(m.GetLog(id)))) + .WithSummary("Registro de scripts de la extensión"); + + g.MapGet("/catalogs", (bool? refresh, ExtensionManager m, CancellationToken ct) => + Guard(async () => Results.Ok(await m.GetCatalogsAsync(refresh == true, ct)))) + .WithSummary("Catálogos y sus extensiones"); + + g.MapPost("/catalogs", (CatalogAddRequest req, ExtensionManager m, CancellationToken ct) => + Guard(async () => Results.Ok(await m.AddCatalogAsync(req.Url, ct)))) + .WithSummary("Añadir un catálogo (repositorio con osms-catalog.json)"); + + g.MapDelete("/catalogs", (string url, ExtensionManager m) => + Guard(() => { m.RemoveCatalog(url); return Task.FromResult(Results.NoContent()); })) + .WithSummary("Quitar un catálogo"); + + // Pestañas: ficheros estáticos del paquete, con un token en la ruta (ver ResolvePanelFile). + // La CSP "sandbox" aísla la página aunque se abra fuera del iframe del panel. + var types = new FileExtensionContentTypeProvider(); + app.MapGet("/ext/{id}/{token}/{**path}", (string id, string token, string? path, HttpContext ctx, ExtensionManager m) => + { + var file = m.ResolvePanelFile(id, token, path ?? ""); + if (file is null) return Results.NotFound(); + var h = ctx.Response.Headers; + h["X-Frame-Options"] = "SAMEORIGIN"; + h["Content-Security-Policy"] = + "sandbox allow-scripts allow-forms allow-popups allow-downloads; frame-ancestors 'self'"; + h["Cache-Control"] = "no-cache"; + h["Cross-Origin-Resource-Policy"] = "same-origin"; + if (!types.TryGetContentType(file, out var type)) type = "application/octet-stream"; + return Results.File(file, type); + }).ExcludeFromDescription(); + + return app; + } + + /// Errores esperables → 400/409/502 con el mensaje (ya traducido), no un 500. + static async Task Guard(Func> action) + { + try { return await action(); } + catch (ExtensionException ex) { return Results.Problem(ex.Message, statusCode: StatusCodes.Status409Conflict); } + catch (GitHubException ex) { return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway); } + catch (HttpRequestException ex) { return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway); } + catch (ExtensionFormatException ex) { return Results.Problem(ex.Message, statusCode: StatusCodes.Status400BadRequest); } + catch (TaskCanceledException ex) { return Results.Problem(ex.Message, statusCode: StatusCodes.Status504GatewayTimeout); } + } +} diff --git a/Core/Api/StreamSessionService.cs b/Core/Api/StreamSessionService.cs index eb044bb..73af24b 100644 --- a/Core/Api/StreamSessionService.cs +++ b/Core/Api/StreamSessionService.cs @@ -572,6 +572,21 @@ private static void MuteRdpClientOnHost(StreamSession session, int clientPid) AudioSessionMuter.StartPersistentMute((uint)clientPid); } + /// Lo que reciben los ganchos de extensiones de esta sesión. + internal static OpenStreamMS.Services.Extensions.HookContext HookContextFor(StreamSession session, string? windowsUser = null) + { + if (windowsUser is null && !session.Local) + { + try + { + var u = ResolveUser(session); + windowsUser = string.IsNullOrWhiteSpace(u.Domain) || u.Domain == "." ? u.Username : $"{u.Domain}\\{u.Username}"; + } + catch { } + } + return new(session.Id, session.Name, session.RdpSessionId, windowsUser, session.Local); + } + private static StreamUserConfig ResolveUser(StreamSession session) { if (session.Isolated) @@ -654,6 +669,11 @@ private void ForceStopInternal(StreamSession session, bool restarting = false) { try { + // Ganchos de extensiones: antes de cerrar nada, con la sesión de Windows aún viva. + if (session.RdpSessionId > 0 && !session.IsComposite) + OpenStreamMS.Services.Extensions.ExtensionManager.Fire( + OpenStreamMS.Services.Extensions.ExtensionEvent.SessionStop, HookContextFor(session)); + // Sunshine corre dentro de la sesión RDP. Si matamos FreeRDP primero, // Windows puede tirar abajo Sunshine antes de que escriba named_devices. // Pararlo primero permite /api/restart -> save_state -> mirror. @@ -1252,6 +1272,8 @@ private void DoStartLocked(StreamSession session, int generation) if (running) { Logger.Log($"[{session.Name}] Sesión activa (RDP={rdpId}).", session.Id); + OpenStreamMS.Services.Extensions.ExtensionManager.Fire( + OpenStreamMS.Services.Extensions.ExtensionEvent.SessionStart, HookContextFor(session)); } else { @@ -1320,6 +1342,8 @@ private void StartLocal(StreamSession session, int generation) } Logger.Log($"[{session.Name}] Sesión local activa (sesión de Windows {consoleId}).", session.Id); + OpenStreamMS.Services.Extensions.ExtensionManager.Fire( + OpenStreamMS.Services.Extensions.ExtensionEvent.SessionStart, HookContextFor(session, $"{domain}\\{username}")); } private SunshineManager GetOrCreateSunshineManager(StreamSession session, diff --git a/Core/wwwroot/extensions.js b/Core/wwwroot/extensions.js new file mode 100644 index 0000000..1b33f0d --- /dev/null +++ b/Core/wwwroot/extensions.js @@ -0,0 +1,426 @@ +// ── Extensiones ───────────────────────────────────────────────────────────── +// Se instalan desde GitHub (un enlace o un catálogo). Antes de instalar se descarga el +// paquete y se enseña qué hace, de quién es y su SHA-256; se instala exactamente eso. +// Las que tienen pestaña la abren en un iframe aislado (sandbox, origen opaco). + +let extState = { installed: [], operation: null, busy: false }; +let extCatalogs = []; +let extTimer = null; +let extPreview = null; // vista previa en el modal de instalación +let extOpWatch = null; // sondeo mientras corre una operación + +function extCapLabel(cap) { return t(`ext.cap.${cap}`); } + +async function loadExtensions() { + const res = await api('GET', '/api/extensions'); + if (!res || !res.ok) return; + extState = await res.json(); + renderExtensionTabs(); + if (activeTab === 'extensions') renderExtensions(); +} + +async function loadExtensionCatalogs(refresh = false) { + const res = await api('GET', `/api/extensions/catalogs${refresh ? '?refresh=true' : ''}`); + if (!res || !res.ok) return; + extCatalogs = await res.json(); + if (activeTab === 'extensions') renderExtensions(); + if (!byId('ext-catalogs-modal').classList.contains('hidden')) renderCatalogList(); +} + +// ── Vista principal ───────────────────────────────────────────────────────── +function renderExtensions() { + const list = extState.installed || []; + byId('ext-count').textContent = list.length; + renderInto(byId('ext-installed-grid'), list.length + ? list.map(extCard).join('') + : `

${esc(t('ext.noneInstalled'))}

`); + + const q = (byId('ext-search').value || '').trim().toLowerCase(); + const rows = []; + for (const c of extCatalogs) { + for (const e of c.extensions || []) { + const text = `${e.name} ${e.description || ''} ${e.repo} ${(e.tags || []).join(' ')}`.toLowerCase(); + if (!q || text.includes(q)) rows.push({ c, e }); + } + } + const errors = extCatalogs.filter(c => c.error) + .map(c => `
${esc(c.name)}: ${esc(t('ext.catalogError', { msg: c.error }))}
`).join(''); + renderInto(byId('ext-available-grid'), errors + (rows.length + ? rows.map(({ c, e }) => extCatalogCard(c, e)).join('') + : `

${esc(t('ext.noneAvailable'))}

`)); +} + +function extChips(caps) { + return (caps || []).map(c => `${esc(extCapLabel(c))}`).join(''); +} + +function extCard(x) { + const status = []; + if (x.broken) status.push(`${esc(t('ext.broken'))}`); + if (!x.enabled) status.push(`${esc(t('ext.disabled'))}`); + if (x.componentInstalled === false) status.push(`${esc(t('ext.componentMissing'))}`); + if (x.rebootPending) status.push(`${esc(t('ext.reboot'))}`); + const cat = extCatalogs.find(c => c.url === x.catalogUrl); + return `
+
+
+
${esc(x.name)}
+
${esc(x.version)} · ${esc(x.repo)}${ + x.author ? ` · ${esc(x.author)}` : ''}
+
+ +
+ ${x.description ? `

${esc(x.description)}

` : ''} +
${extChips(x.capabilities)}${status.join('')}${ + cat ? `${esc(t('ext.fromCatalog', { catalog: cat.name }))}` : ''}
+
`; +} + +function extCatalogCard(c, e) { + const installed = e.installedId ? `${esc(t('ext.installedBadge'))}` : ''; + const pinned = e.sha256Pinned ? `${esc(t('ext.pinned'))}` : ''; + const tags = (e.tags || []).map(tag => `${esc(tag)}`).join(''); + const args = JSON.stringify({ source: e.repo, path: e.path, catalogUrl: c.url }).replace(/"/g, '"'); + return `
+
+
+
${esc(e.name)}
+
${esc(e.repo)}${ + e.path ? '/' + esc(e.path) : ''} · ${esc(c.name)}${c.official ? ` ${esc(t('ext.official'))}` : ''}
+
+
+ ${e.description ? `

${esc(e.description)}

` : ''} +
${installed}${pinned}${tags}
+
+ +
+
`; +} + +function extMenu(e, id) { + const x = (extState.installed || []).find(i => i.id === id); + if (!x) return; + const busy = extState.busy; + openMenu(e, [ + { icon: 'download', label: t('ext.menu.update'), run: () => checkExtUpdate(x), disabled: busy, hint: t('ext.busyHint') }, + { icon: 'power', label: t(x.enabled ? 'ext.menu.disable' : 'ext.menu.enable'), run: () => setExtEnabled(x, !x.enabled) }, + ...(x.componentInstalled !== null && x.componentInstalled !== undefined + ? [{ icon: 'restart', label: t('ext.menu.detect'), run: () => detectExt(x) }] : []), + { icon: 'log', label: t('ext.menu.log'), run: () => openExtLog(x) }, + { icon: 'external', label: t('ext.menu.repo'), run: () => window.open(x.repoUrl, '_blank', 'noopener') }, + { sep: true }, + { icon: 'trash', label: t('ext.menu.uninstall'), run: () => uninstallExt(x), danger: true, disabled: busy, hint: t('ext.busyHint') }, + ]); +} + +// ── Instalar (enlace o catálogo) ──────────────────────────────────────────── +function openExtInstall(req) { + extPreview = null; + byId('ext-install-title').textContent = t('ext.installTitle'); + byId('ext-link').value = req && req.source ? req.source + (req.path ? `/${req.path}` : '') : ''; + byId('ext-link-row').classList.toggle('hidden', !!(req && req.catalogUrl)); + byId('ext-install-error').style.display = 'none'; + byId('ext-preview').innerHTML = ''; + byId('ext-op').classList.add('hidden'); + setExtInstallButtons('check'); + show('ext-install-modal'); + if (req && req.source) checkExt(req); + else byId('ext-link').focus(); +} + +function closeExtInstall() { + hide('ext-install-modal'); + extPreview = null; +} + +function setExtInstallButtons(mode) { + byId('ext-check-btn').classList.toggle('hidden', mode !== 'check'); + byId('ext-install-btn').classList.toggle('hidden', mode !== 'install'); + byId('ext-install-btn').disabled = mode !== 'install' || !byId('ext-trust')?.checked; +} + +function extInstallError(msg) { + const el = byId('ext-install-error'); + el.textContent = msg; + el.style.display = ''; +} + +async function problemText(res) { + try { const j = await res.json(); return j.detail || j.title || res.statusText; } catch { return res.statusText; } +} + +async function checkExt(req) { + req = req || { source: byId('ext-link').value.trim() }; + if (!req.source) return; + byId('ext-install-error').style.display = 'none'; + byId('ext-preview').innerHTML = `

${esc(t('ext.checking'))}

`; + byId('ext-check-btn').disabled = true; + const res = await api('POST', '/api/extensions/preview', req); + byId('ext-check-btn').disabled = false; + if (!res) { byId('ext-preview').innerHTML = ''; return; } + if (!res.ok) { + byId('ext-preview').innerHTML = ''; + extInstallError(await problemText(res)); + return; + } + showExtPreview(await res.json()); +} + +function showExtPreview(p, { update = false } = {}) { + extPreview = p; + byId('ext-install-title').textContent = t(update ? 'ext.updateTitle' : 'ext.installTitle'); + const runAs = p.hookRunAs ? t(`ext.runAs.${p.hookRunAs}`) : ''; + const caps = (p.capabilities || []).map(c => { + const desc = c === 'hooks' ? t('ext.cap.hooks_desc', { runAs, list: (p.hooks || []).join(', ') }) + : c === 'apps' ? t('ext.cap.apps_desc', { list: (p.apps || []).join(', ') }) + : c === 'panel' ? t('ext.cap.panel_desc', { title: p.panelTitle || '' }) + : t(`ext.cap.${c}_desc`); + return `
  • ${esc(extCapLabel(c))} — ${esc(desc)}
  • `; + }).join(''); + const row = (label, value) => value ? `
    ${esc(label)}${value}
    ` : ''; + const notices = [ + p.notice ? `
    ${esc(t('ext.notice'))}
    ${esc(p.notice)}
    ` : '', + p.catalogNotice ? `
    ${esc(t('ext.catalogNotice'))}
    ${esc(p.catalogNotice)}
    ` : '', + p.replacesOtherSource ? `
    ${esc(t('ext.replaces', { version: p.installedVersion || '' }))}
    ` : '', + !p.replacesOtherSource && p.installedVersion ? `

    ${esc(t('ext.updateFrom', { version: p.installedVersion }))}

    ` : '', + !p.compatible ? `
    ${esc(t('ext.incompatible', { min: p.minOsmsVersion || '?' }))}
    ` : '', + ].join(''); + const author = p.author || t('ext.unknownAuthor'); + + byId('ext-preview').innerHTML = ` +
    +

    ${esc(p.name)} ${esc(p.id)}

    + ${p.description ? `

    ${esc(p.description)}

    ` : ''} +
    +
    + ${row(t('ext.author'), esc(author))} + ${row(t('ext.repo'), `${esc(p.repo)}${p.path ? '/' + esc(p.path) : ''}`)} + ${row(t('ext.version'), `${esc(p.version)} (${esc(t(p.isRelease ? 'ext.release' : 'ext.commitOnly'))})`)} + ${row(t('ext.commit'), `${esc(p.commit)}`)} + ${row(t('ext.sha256'), `${esc(p.sha256)}
    ${esc(t(p.sha256Pinned ? 'ext.sha256Pinned' : 'ext.sha256Unpinned'))}`)} + ${row(t('ext.license'), esc(p.license || ''))} + ${p.homepage ? row(t('ext.homepage'), `${esc(p.homepage)}`) : ''} +
    + + ${notices} +
    ${esc(t('ext.systemWarning'))}
    + `; + byId('ext-install-btn').textContent = plainLabel(t(update || p.installedVersion ? 'ext.update' : 'ext.install')); + setExtInstallButtons(p.compatible ? 'install' : 'none'); +} + +async function installExt() { + if (!extPreview || !byId('ext-trust').checked) return; + const p = extPreview; + let replace = false; + if (p.replacesOtherSource) { + replace = await ask(t('ext.replaces', { version: p.installedVersion || '' }), { danger: true, ok: t('ext.install') }); + if (!replace) return; + } + const res = await api('POST', '/api/extensions/install', { token: p.token, sha256: p.sha256, replace }); + if (!res) return; + if (!res.ok) { extInstallError(await problemText(res)); return; } + setExtInstallButtons('none'); + watchExtOperation(true); +} + +// Sigue la operación en curso: log en el modal (si está abierto) y aviso al terminar. +function watchExtOperation(inModal) { + clearInterval(extOpWatch); + if (inModal) byId('ext-op').classList.remove('hidden'); + const tick = async () => { + await loadExtensions(); + if (inModal) { + const res = await api('GET', '/api/extensions/operation/log'); + if (res && res.ok) { + const pre = byId('ext-op-log'); + pre.textContent = (await res.json()).lines.join('\n'); + pre.scrollTop = pre.scrollHeight; + } + } + const op = extState.operation; + byId('ext-op-state').textContent = op ? t(`ext.kind.${op.kind}`, { name: op.name }) : ''; + if (extState.busy) return; + clearInterval(extOpWatch); + extOpWatch = null; + if (!op) return; + if (op.state === 'ok') { + const done = op.kind === 'uninstall' ? 'ext.uninstalledOk' : 'ext.installedOk'; + toast([t(done, { name: op.name }), op.rebootRequired ? t('ext.rebootRequired') : '', + op.kind !== 'uninstall' ? t('ext.restartSessions') : ''].filter(Boolean).join(' ')); + if (inModal) closeExtInstall(); + loadExtensionCatalogs(); + } else if (op.state === 'error') { + if (inModal) extInstallError(t('ext.opError', { msg: op.message || '' })); + else toast(t('ext.opError', { msg: op.message || '' }), true); + } + }; + extOpWatch = setInterval(tick, 1000); + tick(); +} + +// ── Acciones sobre una instalada ──────────────────────────────────────────── +async function checkExtUpdate(x) { + toast(t('ext.checking')); + const res = await api('GET', `/api/extensions/${encodeURIComponent(x.id)}/update`); + if (!res) return; + if (!res.ok) { toast(await problemText(res), true); return; } + const u = await res.json(); + if (u.upToDate) { toast(t('ext.upToDate', { name: x.name, version: u.currentVersion })); return; } + openExtInstall(null); + byId('ext-link-row').classList.add('hidden'); + showExtPreview(u.preview, { update: true }); +} + +async function setExtEnabled(x, enabled) { + const res = await api('POST', `/api/extensions/${encodeURIComponent(x.id)}/enabled`, { enabled }); + if (res && !res.ok) toast(await problemText(res), true); + else if (res) toast(t('ext.restartSessions')); + loadExtensions(); +} + +async function detectExt(x) { + const res = await api('POST', `/api/extensions/${encodeURIComponent(x.id)}/detect`); + if (res && !res.ok) toast(await problemText(res), true); + loadExtensions(); +} + +async function uninstallExt(x) { + const extra = x.componentInstalled !== null && x.componentInstalled !== undefined ? t('ext.confirmUninstallComponent') : ''; + if (!await ask(t('ext.confirmUninstall', { name: x.name, extra }), { danger: true, ok: t('ext.menu.uninstall') })) return; + const res = await api('POST', `/api/extensions/${encodeURIComponent(x.id)}/uninstall`); + if (!res) return; + if (!res.ok) { toast(await problemText(res), true); return; } + if (activeTab === `ext:${x.id}`) switchTab('extensions'); + watchExtOperation(false); +} + +async function openExtLog(x) { + byId('ext-log-title').textContent = t('ext.logTitle', { name: x.name }); + byId('ext-log-body').textContent = t('empty.loading'); + show('ext-log-modal'); + const res = await api('GET', `/api/extensions/${encodeURIComponent(x.id)}/log`); + if (!res || !res.ok) return; + const lines = (await res.json()).lines; + byId('ext-log-body').textContent = lines.length ? lines.join('\n') : t('ext.noLog'); +} + +// ── Catálogos ─────────────────────────────────────────────────────────────── +function openCatalogs() { + byId('ext-catalog-error').style.display = 'none'; + byId('ext-catalog-url').value = ''; + renderCatalogList(); + show('ext-catalogs-modal'); +} + +function renderCatalogList() { + byId('ext-catalog-list').innerHTML = extCatalogs.length ? extCatalogs.map(c => ` +
    +
    + ${esc(c.name)}${c.official ? ` ${esc(t('ext.official'))}` : ''} + + ${c.error ? `
    ${esc(t('ext.catalogError', { msg: c.error }))}
    ` + : `
    ${esc(c.description || '')}
    `} +
    + +
    `).join('') : `

    ${esc(t('ext.noCatalogs'))}

    `; +} + +async function addCatalog(ev) { + ev.preventDefault(); + const url = byId('ext-catalog-url').value.trim(); + if (!url) return; + const btn = byId('ext-catalog-add'); + btn.disabled = true; + const res = await api('POST', '/api/extensions/catalogs', { url }); + btn.disabled = false; + if (!res) return; + if (!res.ok) { + const el = byId('ext-catalog-error'); + el.textContent = await problemText(res); + el.style.display = ''; + return; + } + byId('ext-catalog-url').value = ''; + toast(t('ext.catalogAdded')); + await loadExtensionCatalogs(); +} + +async function removeCatalog(url, name) { + if (!await ask(t('ext.confirmRemoveCatalog', { name }), { danger: true, ok: t('ext.catalogRemove') })) return; + const res = await api('DELETE', `/api/extensions/catalogs?url=${encodeURIComponent(url)}`); + if (res && !res.ok) { toast(await problemText(res), true); return; } + await loadExtensionCatalogs(); +} + +// ── Pestañas propias de las extensiones ───────────────────────────────────── +function renderExtensionTabs() { + const bar = document.querySelector('.tabs'); + const wanted = (extState.installed || []).filter(x => x.panelUrl); + bar.querySelectorAll('.tab[data-ext]').forEach(b => { + if (!wanted.some(x => x.id === b.dataset.ext)) b.remove(); + }); + for (const x of wanted) { + let b = bar.querySelector(`.tab[data-ext="${CSS.escape(x.id)}"]`); + if (!b) { + b = document.createElement('button'); + b.className = 'tab'; + b.type = 'button'; + b.dataset.ext = x.id; + b.onclick = () => switchTab(`ext:${x.id}`); + bar.appendChild(b); + } + b.textContent = x.panelTitle; + b.title = x.name; + b.classList.toggle('active', activeTab === `ext:${x.id}`); + } + if (activeTab.startsWith('ext:') && !wanted.some(x => `ext:${x.id}` === activeTab)) switchTab('extensions'); + moveTabIndicator(); +} + +function showExtensionPanel(id) { + const x = (extState.installed || []).find(i => i.id === id); + const frame = byId('ext-frame'); + if (!x || !x.panelUrl) { frame.removeAttribute('src'); return; } + if (frame.dataset.ext !== id) { + frame.dataset.ext = id; + frame.src = x.panelUrl; + } +} + +// Canal de solo lectura para las pestañas: el iframe (origen opaco) no ve la API. +// Pide { osms: 'context' } y recibe idioma, tema, sesiones y puestos (sin credenciales). +window.addEventListener('message', ev => { + const frame = byId('ext-frame'); + if (!frame || ev.source !== frame.contentWindow || !ev.data || ev.data.osms !== 'context') return; + frame.contentWindow.postMessage({ + osms: 'context', + extension: frame.dataset.ext, + lang: window.I18n ? I18n.lang : 'en', + theme: document.documentElement.dataset.theme || '', + sessions: (sessions || []).map(s => ({ id: s.id, name: s.name, state: s.state, local: !!s.local })), + seats: (typeof seats !== 'undefined' ? seats : []).map(s => ({ id: s.id, name: s.name, state: s.state })), + }, '*'); +}); + +// ── Arranque ──────────────────────────────────────────────────────────────── +function enterExtensionsTab() { + renderExtensions(); + loadExtensions(); + loadExtensionCatalogs(); + if (!extTimer) extTimer = setInterval(whenVisible(loadExtensions), 5000); +} + +function leaveExtensionsTab() { + clearInterval(extTimer); + extTimer = null; +} + +document.addEventListener('DOMContentLoaded', async () => { + if (!await I18n.ready) return; + await loadExtensions(); + if (location.hash === '#extensions') switchTab('extensions'); + else if (location.hash.startsWith('#ext:')) switchTab(location.hash.slice(1)); +}); +window.addEventListener('langchange', () => { if (activeTab === 'extensions') renderExtensions(); }); diff --git a/Core/wwwroot/index.html b/Core/wwwroot/index.html index 735e9a8..0c04970 100644 --- a/Core/wwwroot/index.html +++ b/Core/wwwroot/index.html @@ -88,6 +88,7 @@ + @@ -124,6 +125,36 @@

    Cargando…

    + + + + + + @@ -643,6 +674,68 @@

    Diagnóstico

    + + + + + + + + +