diff --git a/Core/Api/SeatEndpoints.cs b/Core/Api/SeatEndpoints.cs index c954185..872833f 100644 --- a/Core/Api/SeatEndpoints.cs +++ b/Core/Api/SeatEndpoints.cs @@ -6,13 +6,17 @@ namespace OpenStreamMS.Core.Api; // ── DTOs ── public record SeatMonitorDto(string DevicePath, string FriendlyName, int Width, int Height, int RefreshHz, SeatScreenArea Area = SeatScreenArea.Full); -public record SeatDeviceDto(SeatDeviceKind Kind, string UsbPort, string Label); +/// Hay algo conectado en ese puerto (solo en respuestas; se ignora al guardar). +/// Otro dispositivo que abre un servicio del sistema ("storage", "camera" o +/// "audio"): la reserva por ACL no lo aísla. Solo en respuestas. +public record SeatDeviceDto(SeatDeviceKind Kind, string UsbPort, string Label, bool Present = true, string? SystemOpened = null); public record SeatDto( Guid Id, string Name, SeatMonitorDto? Monitor, string? AudioOutId, string? AudioOutName, List Devices, Guid? SessionId, bool AutoStart, bool ExclusiveSession, string State, string? StatusDetail, string? ErrorMessage, - string? AudioInId = null, string? AudioInName = null); + string? AudioInId = null, string? AudioInName = null, + bool GamepadsIsolated = true); public record SeatUpsertRequest( string Name, SeatMonitorDto? Monitor, string? AudioOutId, string? AudioOutName, @@ -137,8 +141,11 @@ private static Seat FromRequest(Seat seat, SeatUpsertRequest req) s.Id, s.Name, s.Monitor is { } m ? new SeatMonitorDto(m.DevicePath, m.FriendlyName, m.Width, m.Height, m.RefreshHz, m.Area) : null, s.AudioOutId, s.AudioOutName, - s.Devices.Select(d => new SeatDeviceDto(d.Kind, d.UsbPort, d.Label)).ToList(), + s.Devices.Select(d => new SeatDeviceDto(d.Kind, d.UsbPort, d.Label, + OpenStreamMS.Core.Helpers.DeviceTopology.IsPortPresent(d.UsbPort), + d.Kind == SeatDeviceKind.Other ? SeatDeviceAccess.SystemOpenedKind(d.UsbPort) : null)).ToList(), s.SessionId, s.AutoStart, s.ExclusiveSession, s.State.ToString(), s.StatusDetail, s.ErrorMessage, - s.AudioInId, s.AudioInName); + s.AudioInId, s.AudioInName, + OpenStreamMS.Services.Gamepad.GamepadSessionIsolation.SessionJailSupported); } diff --git a/Core/Api/SessionEndpoints.cs b/Core/Api/SessionEndpoints.cs index 35c753e..1f2b167 100644 --- a/Core/Api/SessionEndpoints.cs +++ b/Core/Api/SessionEndpoints.cs @@ -173,6 +173,13 @@ StreamProtocol Protocol ); /// Cuerpo para activar o desactivar el auto-arranque de una sesión. +/// Mando físico asignado a una sesión de stream. +/// Hay algo conectado en ese puerto (solo en respuestas). +public record SessionGamepadDto(string UsbPort, string Label, bool Present = true); + +/// Mandos físicos de la sesión (sustituye la lista entera; vacía = ninguno). +public record SetGamepadsRequest(List Gamepads); + public record SetEnabledRequest( /// true para habilitar el auto-arranque al reiniciar el servicio; false para deshabilitarlo. bool Enabled @@ -257,6 +264,10 @@ public record SessionResponse( RdpCompositionMode RdpComposition = RdpCompositionMode.Smooth, /// Paso del arranque en el que falló (user, rdp, profile, unlock, sunshine); null si no hay error. string? FailedPhase = null, + /// Mandos físicos asignados a la sesión. + List? Gamepads = null, + /// HidHide puede aislar los mandos por sesión (si no, los asignados se ven en todas). + bool GamepadsIsolated = true, /// Solo en una sesión compuesta: sus huecos en orden (el mando N va al hueco N). IReadOnlyList? Composite = null, /// Solo en una sesión compuesta: sesión del teclado, el ratón y el audio. @@ -490,6 +501,17 @@ al arrancar o reiniciarse. El cambio se persiste en sessions.json. aplica los cambios y la vuelve a iniciar. """); + // PUT /api/sessions/{id}/gamepads + group.MapPut("/{id:guid}/gamepads", SetGamepads) + .WithName("SetSessionGamepads") + .WithSummary("Asignar mandos físicos a la sesión") + .WithDescription(""" + Mandos conectados a este PC (por puerto USB) que juegan en la sesión: mientras está + en marcha solo los ve su sesión de Windows y el juego los lee directamente, sin pasar + por el cliente ni la red. Funciona en caliente, sin reiniciar la sesión. Un puesto + encendido que tenga el mismo puerto tiene prioridad. + """); + // PUT /api/sessions/{id}/protocol group.MapPut("/{id:guid}/protocol", SetStreamProtocol) .WithName("SetSessionStreamProtocol") @@ -713,6 +735,27 @@ static Results, NotFound> Restart( return TypedResults.Accepted($"/api/sessions/{id}", ToResponse(session)); } + static Results, NotFound> SetGamepads( + Guid id, SetGamepadsRequest req, StreamSessionService svc) + { + try + { + var pads = (req.Gamepads ?? []) + .Where(g => !string.IsNullOrWhiteSpace(g.UsbPort)) + .DistinctBy(g => g.UsbPort, StringComparer.OrdinalIgnoreCase) + .Select(g => new OpenStreamMS.Services.Seats.SeatDevice + { + Kind = OpenStreamMS.Services.Seats.SeatDeviceKind.Gamepad, UsbPort = g.UsbPort, Label = g.Label ?? "", + }) + .ToList(); + return TypedResults.Ok(ToResponse(svc.SetGamepads(id, pads))); + } + catch (KeyNotFoundException) + { + return TypedResults.NotFound(); + } + } + static Results, NotFound> SetEnabled( Guid id, SetEnabledRequest req, StreamSessionService svc) { @@ -1011,5 +1054,8 @@ static async Task UnpairAllClients( StreamSessionService.SteamLoginState(s), s.RdpDisplayScale, s.RdpComposition, s.ErrorMessage is null ? null : s.FailedPhase, + s.Gamepads.Select(g => new SessionGamepadDto(g.UsbPort, g.Label, + OpenStreamMS.Core.Helpers.DeviceTopology.IsPortPresent(g.UsbPort))).ToList(), + OpenStreamMS.Services.Gamepad.GamepadSessionIsolation.SessionJailSupported, s.Composite, s.CompositeInput, s.CompositeOf); } diff --git a/Core/Api/StreamSession.cs b/Core/Api/StreamSession.cs index 104bfa1..4e20614 100644 --- a/Core/Api/StreamSession.cs +++ b/Core/Api/StreamSession.cs @@ -146,6 +146,14 @@ public class StreamSession /// public string? IsolatedUsername { get; set; } + /// + /// Mandos físicos (por puerto USB, como en los puestos) que juegan en esta sesión: mientras + /// está en marcha solo los ve su sesión de Windows, y el juego los lee directamente por USB, sin + /// pasar por el cliente, la red y el mando virtual de Sunshine (menos latencia). Al pararla + /// vuelven a la consola. Un puesto encendido que reclame el mismo puerto tiene prioridad. + /// + public List Gamepads { get; set; } = []; + /// Usuario de Windows dedicado de una sesión aislada. public string GetIsolatedUser() => IsolatedUsername ?? OpenStreamMS.Core.Helpers.IsolatedUserManager.GetUsername(Id); diff --git a/Core/Api/StreamSessionService.cs b/Core/Api/StreamSessionService.cs index 5a2953f..eb044bb 100644 --- a/Core/Api/StreamSessionService.cs +++ b/Core/Api/StreamSessionService.cs @@ -209,6 +209,43 @@ public bool Delete(Guid id, bool keepUser = false) return true; } + /// Mandos físicos de la sesión; GamepadSessionIsolation los mueve en su siguiente pasada. + public StreamSession SetGamepads(Guid id, List gamepads) + { + var session = RequireSession(id); + session.Gamepads = gamepads; + Logger.Log($"[{session.Name}] Mandos físicos asignados: {(gamepads.Count == 0 ? "ninguno" : string.Join(", ", gamepads.Select(g => g.Label)))}.", id); + SaveSessions(); + return session; + } + + /// + /// Sesión de Windows de la sesión de stream en marcha que tiene ese mando asignado, o false. + /// Las sesiones locales corren en la consola: no cuentan (el mando ya va a la consola). + /// + public bool TryGetGamepadWindowsSession(string usbPort, out uint windowsSession) + { + windowsSession = 0; + foreach (var s in _sessions.Values) + { + if (s.Local || s.State != SessionState.Running || s.RdpSessionId == 0) continue; + if (!s.Gamepads.Any(g => g.UsbPort.Equals(usbPort, StringComparison.OrdinalIgnoreCase))) continue; + windowsSession = s.RdpSessionId; + return true; + } + return false; + } + + /// + /// Huella de las asignaciones de mandos en vigor (puerto → sesión de Windows): si cambia + /// (sesión arrancada o parada, mandos editados), GamepadSessionIsolation reasigna al momento. + /// + public string GamepadAssignmentSignature() => + string.Join('|', _sessions.Values + .Where(s => !s.Local && s.State == SessionState.Running && s.RdpSessionId != 0 && s.Gamepads.Count > 0) + .OrderBy(s => s.Id) + .Select(s => $"{s.RdpSessionId}:{string.Join(',', s.Gamepads.Select(g => g.UsbPort))}")); + public StreamSession SetEnabled(Guid id, bool enabled) { var session = RequireSession(id); diff --git a/Core/Helpers/DeviceTopology.cs b/Core/Helpers/DeviceTopology.cs index 9445e1b..881abc6 100644 --- a/Core/Helpers/DeviceTopology.cs +++ b/Core/Helpers/DeviceTopology.cs @@ -20,7 +20,7 @@ public static class DeviceTopology private const int CM_GETIDLIST_FILTER_PRESENT = 0x100; private const int CM_GETIDLIST_FILTER_CLASS = 0x200; - /// Teclados, ratones y mandos físicos conectados por USB, uno por puerto y tipo. + /// Teclados, ratones, mandos y otros dispositivos USB externos, uno por puerto y tipo. public static List EnumerateInputDevices() { var result = new List(); @@ -41,9 +41,69 @@ void Add(IEnumerable ids, SeatDeviceKind kind) Add(GamepadSessionIsolation.Cm.DeviceIds(KeyboardClass, CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT) .Where(IsBootKeyboard), SeatDeviceKind.Keyboard); Add(GamepadSessionIsolation.Cm.GameControllers(), SeatDeviceKind.Gamepad); + + // El resto de USB externos, uno por puerto: los que ya salen como teclado, ratón o mando + // no se repiten, y se dejan fuera hubs, radios Bluetooth y lo que va dentro del equipo + // (controladores RGB, lectores de tarjetas internos…), que no tiene sentido dar a un puesto. + var taken = result.Select(d => d.UsbPort).ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var usb in GamepadSessionIsolation.Cm.DeviceIds("USB")) + { + if (usb.Contains("&MI_", StringComparison.OrdinalIgnoreCase) || usb.StartsWith(@"USB\ROOT_HUB", StringComparison.OrdinalIgnoreCase)) continue; + if (IsHubOrRadio(usb) || IsInternal(usb)) continue; + var port = LocationPath(usb) ?? usb; + if (!taken.Add(port)) continue; + result.Add(new InputDeviceInfo(usb, SeatDeviceKind.Other, port, DisplayName(usb))); + } return result; } + private const string UsbHubClassGuid = "{36fc9e60-c465-11cf-8056-444553540000}"; // clase USB (hubs y controladoras) + private const string BluetoothClassGuid = "{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}"; + + /// Hub USB o radio Bluetooth: darlos a un puesto arrastraría todo lo que cuelga de ellos. + private static bool IsHubOrRadio(string usb) + { + var cls = GamepadSessionIsolation.Cm.ClassGuidOf(usb); + if (string.Equals(cls, BluetoothClassGuid, StringComparison.OrdinalIgnoreCase)) return true; + return string.Equals(cls, UsbHubClassGuid, StringComparison.OrdinalIgnoreCase) && + Strings(usb, CompatibleIds).Any(c => c.StartsWith(@"USB\Class_09", StringComparison.OrdinalIgnoreCase)); + } + + /// Va dentro del equipo (DEVPKEY_Device_InLocalMachineContainer). + private static bool IsInternal(string usb) + { + var key = InLocalMachineContainer; + if (CM_Locate_DevNodeW(out int inst, usb, 0) != 0) return false; + int size = 1; + var buf = new byte[1]; + return CM_Get_DevNode_PropertyW(inst, ref key, out _, buf, ref size, 0) == 0 && buf[0] != 0; + } + + private static readonly object _portsLock = new(); + private static HashSet _presentPorts = new(StringComparer.OrdinalIgnoreCase); + private static long _presentPortsAt = -1; + + /// + /// Puertos USB con algo conectado ahora (caché de 2 s: el panel lo consulta a menudo). Un + /// puerto asignado que no aparece es un dispositivo desenchufado, o un puerto que cambió de + /// ruta (hub o dock distinto, otra ranura PCI): el puesto arrancaría sin él sin avisar. + /// + public static bool IsPortPresent(string usbPort) + { + lock (_portsLock) + { + if (_presentPortsAt < 0 || Environment.TickCount64 - _presentPortsAt > 2000) + { + _presentPorts = GamepadSessionIsolation.Cm.DeviceIds("USB") + .Where(id => !id.Contains("&MI_", StringComparison.OrdinalIgnoreCase)) + .Select(id => LocationPath(id) ?? id) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + _presentPortsAt = Environment.TickCount64; + } + return _presentPorts.Contains(usbPort); + } + } + /// Puerto USB de cualquier nodo (colección HID, XUSB…), o null si no cuelga de un USB. public static string? UsbPortOf(string instanceId) => UsbDeviceOf(instanceId) is { } usb ? LocationPath(usb) ?? usb : null; @@ -89,6 +149,7 @@ private struct DEVPROPKEY { public Guid fmtid; public uint pid; } private static DEVPROPKEY BusReportedDesc => new() { fmtid = new Guid("540b947e-8b40-45bc-a8a2-6a0b894cbda2"), pid = 4 }; private static DEVPROPKEY CompatibleIds => new() { fmtid = DeviceProps, pid = 4 }; + private static DEVPROPKEY InLocalMachineContainer => new() { fmtid = new Guid("8c7ed206-3f8a-4827-b3ab-ae9e1faefc6c"), pid = 4 }; /// La colección de teclado cuelga de una interfaz USB de teclado "boot". private static bool IsBootKeyboard(string keyboardInstance) => diff --git a/Core/wwwroot/app.js b/Core/wwwroot/app.js index eb646d8..2865e4b 100644 --- a/Core/wwwroot/app.js +++ b/Core/wwwroot/app.js @@ -170,7 +170,9 @@ function renderCard(s) { ${power} -
${protos.join('')}${sessionSeatLine(s)}${clientsChip(s)}${compositeMemberChip(s)}
+
${protos.join('')}${sessionSeatLine(s)}${padsChip(s)}${clientsChip(s)}${compositeMemberChip(s)}
+ ${s.gamepads && s.gamepads.length && s.gamepadsIsolated === false + ? `
${esc(t('pads.notIsolated'))}
` : ''} ${metricsSlot(s)} ${startProgress(s)} ${rdpWarning(s)} @@ -202,6 +204,9 @@ function sessionMenu(e, id) { { icon: 'link', label: t('ux.connect.btn'), run: () => openSunMgrModal(s.id), disabled: !running, hint: t('btn.sunshine_disabled_title') }, { icon: 'external', label: t('btn.panel'), run: () => openSunshinePanel(s.id), disabled: !running, hint: t('btn.panel_disabled_title') }, { icon: 'log', label: t('btn.log'), run: () => openLogModal(s.id, s.name) }, + ...(s.composite ? [] : [ + { icon: 'gamepad', label: t('pads.menu'), run: () => openPadsModal(s.id), disabled: s.local, hint: t('pads.localDisabled') }, + ]), s.composite ? { icon: 'grid', label: t('comp.edit'), run: () => openCompositeModal(s.id), disabled: running || busy, hint: t('comp.stopToEdit') } : { icon: 'gear', label: t('btn.settings'), run: () => openEditModal(s.id) }, @@ -219,6 +224,57 @@ function clientsChip(s) { n === 0 ? t('ux.clients.none') : n === 1 ? t('ux.clients.one') : t('ux.clients.many', { n }))}`; } +// Mandos físicos asignados a la sesión (los lee el juego directamente, sin pasar por el cliente). +function padsChip(s) { + const pads = s.gamepads || []; + if (!pads.length) return ''; + const missing = pads.filter(p => p.present === false).map(p => p.label); + const title = pads.map(p => p.label + (p.present === false ? ` (${t('seat.deviceMissing')})` : '')).join(', '); + return `${uiIcon('gamepad')}${esc( + pads.length === 1 ? t('pads.chip.one') : t('pads.chip.many', { n: pads.length }))}`; +} + +// ── Mandos físicos de una sesión ────────────────────────────────────────── +let padsSessionId = null; + +async function openPadsModal(id) { + const s = sessions.find(x => x.id === id); + if (!s) return; + padsSessionId = id; + byId('pads-title').textContent = `${t('pads.title')} · ${s.name}`; + const box = byId('pads-list'); + box.innerHTML = `${esc(t('log.updating'))}`; + show('pads-modal'); + + // Libres (sin puesto ni otra sesión) más los que ya tiene esta sesión, aunque estén desconectados. + const res = await api('GET', '/api/seats/inventory'); + const inv = res && res.ok ? await res.json() : { devices: [] }; + const pads = inv.devices.filter(d => d.kind === 'Gamepad').map(d => ({ usbPort: d.usbPort, name: d.name, missing: false })); + const mine = new Set((s.gamepads || []).map(g => g.usbPort)); + for (const g of (s.gamepads || [])) + if (!pads.some(p => p.usbPort === g.usbPort)) pads.push({ usbPort: g.usbPort, name: g.label, missing: g.present === false }); + + box.innerHTML = pads.length + ? pads.map(p => ``).join('') + : `${esc(t('pads.none'))}`; +} + +async function saveSessionPads() { + const id = padsSessionId; + const s = sessions.find(x => x.id === id); + const gamepads = [...byId('pads-list').querySelectorAll('input:checked')] + .map(el => ({ usbPort: el.value, label: el.dataset.name })); + const res = await api('PUT', `/api/sessions/${id}/gamepads`, { gamepads }); + if (!res || !res.ok) { toast(t('pads.saveError'), true); return; } + hide('pads-modal'); + toast(t('pads.saved', { name: s ? s.name : '' })); + loadSessions(); +} + // Puesto local asociado a la sesión: su nombre y si ahora mismo la está usando. function sessionSeatLine(s) { const seat = seats.find(x => x.sessionId === s.id); @@ -1320,6 +1376,7 @@ async function powerAction(kind) { // Iconos de trazo (heredan el color del texto). const UI_ICONS = { + gamepad: '', power: '', grid: '', copy: '', diff --git a/Core/wwwroot/index.html b/Core/wwwroot/index.html index 3eba49f..735e9a8 100644 --- a/Core/wwwroot/index.html +++ b/Core/wwwroot/index.html @@ -663,6 +663,24 @@

+ + +