Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions Core/Api/SeatEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
/// <param name="Present">Hay algo conectado en ese puerto (solo en respuestas; se ignora al guardar).</param>
/// <param name="SystemOpened">Otro dispositivo que abre un servicio del sistema ("storage", "camera" o
/// "audio"): la reserva por ACL no lo aísla. Solo en respuestas.</param>
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<SeatDeviceDto> 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,
Expand Down Expand Up @@ -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);
}
46 changes: 46 additions & 0 deletions Core/Api/SessionEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,13 @@ StreamProtocol Protocol
);

/// <summary>Cuerpo para activar o desactivar el auto-arranque de una sesión.</summary>
/// <summary>Mando físico asignado a una sesión de stream.</summary>
/// <param name="Present">Hay algo conectado en ese puerto (solo en respuestas).</param>
public record SessionGamepadDto(string UsbPort, string Label, bool Present = true);

/// <summary>Mandos físicos de la sesión (sustituye la lista entera; vacía = ninguno).</summary>
public record SetGamepadsRequest(List<SessionGamepadDto> Gamepads);

public record SetEnabledRequest(
/// <summary>true para habilitar el auto-arranque al reiniciar el servicio; false para deshabilitarlo.</summary>
bool Enabled
Expand Down Expand Up @@ -257,6 +264,10 @@ public record SessionResponse(
RdpCompositionMode RdpComposition = RdpCompositionMode.Smooth,
/// <summary>Paso del arranque en el que falló (user, rdp, profile, unlock, sunshine); null si no hay error.</summary>
string? FailedPhase = null,
/// <summary>Mandos físicos asignados a la sesión.</summary>
List<SessionGamepadDto>? Gamepads = null,
/// <summary>HidHide puede aislar los mandos por sesión (si no, los asignados se ven en todas).</summary>
bool GamepadsIsolated = true,
/// <summary>Solo en una sesión compuesta: sus huecos en orden (el mando N va al hueco N).</summary>
IReadOnlyList<CompositeSlot>? Composite = null,
/// <summary>Solo en una sesión compuesta: sesión del teclado, el ratón y el audio.</summary>
Expand Down Expand Up @@ -490,6 +501,17 @@ Actualiza la configuración de la sesión (nombre, resolución, puerto de Sunshi
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")
Expand Down Expand Up @@ -713,6 +735,27 @@ static Results<Accepted<SessionResponse>, NotFound> Restart(
return TypedResults.Accepted($"/api/sessions/{id}", ToResponse(session));
}

static Results<Ok<SessionResponse>, 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<Ok<SessionResponse>, NotFound> SetEnabled(
Guid id, SetEnabledRequest req, StreamSessionService svc)
{
Expand Down Expand Up @@ -1011,5 +1054,8 @@ static async Task<IResult> 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);
}
8 changes: 8 additions & 0 deletions Core/Api/StreamSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,14 @@ public class StreamSession
/// </summary>
public string? IsolatedUsername { get; set; }

/// <summary>
/// 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.
/// </summary>
public List<OpenStreamMS.Services.Seats.SeatDevice> Gamepads { get; set; } = [];

/// <summary>Usuario de Windows dedicado de una sesión aislada.</summary>
public string GetIsolatedUser() =>
IsolatedUsername ?? OpenStreamMS.Core.Helpers.IsolatedUserManager.GetUsername(Id);
Expand Down
37 changes: 37 additions & 0 deletions Core/Api/StreamSessionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,43 @@ public bool Delete(Guid id, bool keepUser = false)
return true;
}

/// <summary>Mandos físicos de la sesión; GamepadSessionIsolation los mueve en su siguiente pasada.</summary>
public StreamSession SetGamepads(Guid id, List<OpenStreamMS.Services.Seats.SeatDevice> 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;
}

/// <summary>
/// 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).
/// </summary>
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;
}

/// <summary>
/// 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.
/// </summary>
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);
Expand Down
63 changes: 62 additions & 1 deletion Core/Helpers/DeviceTopology.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static class DeviceTopology
private const int CM_GETIDLIST_FILTER_PRESENT = 0x100;
private const int CM_GETIDLIST_FILTER_CLASS = 0x200;

/// <summary>Teclados, ratones y mandos físicos conectados por USB, uno por puerto y tipo.</summary>
/// <summary>Teclados, ratones, mandos y otros dispositivos USB externos, uno por puerto y tipo.</summary>
public static List<InputDeviceInfo> EnumerateInputDevices()
{
var result = new List<InputDeviceInfo>();
Expand All @@ -41,9 +41,69 @@ void Add(IEnumerable<string> 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}";

/// <summary>Hub USB o radio Bluetooth: darlos a un puesto arrastraría todo lo que cuelga de ellos.</summary>
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));
}

/// <summary>Va dentro del equipo (DEVPKEY_Device_InLocalMachineContainer).</summary>
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<string> _presentPorts = new(StringComparer.OrdinalIgnoreCase);
private static long _presentPortsAt = -1;

/// <summary>
/// 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.
/// </summary>
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);
}
}

/// <summary>Puerto USB de cualquier nodo (colección HID, XUSB…), o null si no cuelga de un USB.</summary>
public static string? UsbPortOf(string instanceId) =>
UsbDeviceOf(instanceId) is { } usb ? LocationPath(usb) ?? usb : null;
Expand Down Expand Up @@ -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 };

/// <summary>La colección de teclado cuelga de una interfaz USB de teclado "boot".</summary>
private static bool IsBootKeyboard(string keyboardInstance) =>
Expand Down
59 changes: 58 additions & 1 deletion Core/wwwroot/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,9 @@ function renderCard(s) {
</div>
${power}
</div>
<div class="card-chips">${protos.join('')}${sessionSeatLine(s)}${clientsChip(s)}${compositeMemberChip(s)}</div>
<div class="card-chips">${protos.join('')}${sessionSeatLine(s)}${padsChip(s)}${clientsChip(s)}${compositeMemberChip(s)}</div>
${s.gamepads && s.gamepads.length && s.gamepadsIsolated === false
? `<div class="card-warning">${esc(t('pads.notIsolated'))}</div>` : ''}
${metricsSlot(s)}
${startProgress(s)}
${rdpWarning(s)}
Expand Down Expand Up @@ -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) },
Expand All @@ -219,6 +224,57 @@ function clientsChip(s) {
n === 0 ? t('ux.clients.none') : n === 1 ? t('ux.clients.one') : t('ux.clients.many', { n }))}</span>`;
}

// 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 `<span class="chip chip-pads${missing.length ? ' chip-missing' : ''}" title="${esc(title)}">${uiIcon('gamepad')}${esc(
pads.length === 1 ? t('pads.chip.one') : t('pads.chip.many', { n: pads.length }))}</span>`;
}

// ── 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 = `<span class="muted">${esc(t('log.updating'))}</span>`;
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 => `<label class="dev-check" title="${esc(p.usbPort)}">
<input type="checkbox" value="${esc(p.usbPort)}" data-name="${esc(p.name)}" ${mine.has(p.usbPort) ? 'checked' : ''}>
<span>${esc(p.name)}</span>
${p.missing ? `<span class="dev-kind">${esc(t('seat.deviceMissing'))}</span>` : ''}
</label>`).join('')
: `<span class="muted">${esc(t('pads.none'))}</span>`;
}

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);
Expand Down Expand Up @@ -1320,6 +1376,7 @@ async function powerAction(kind) {

// Iconos de trazo (heredan el color del texto).
const UI_ICONS = {
gamepad: '<path d="M6 11h4M8 9v4M15 12h.01M18 10h.01"/><path d="M17.3 5H6.7a4 4 0 0 0-3.9 3.2l-1 5.2A3 3 0 0 0 7 16.8L8.6 15h6.8l1.6 1.8a3 3 0 0 0 5.2-3.4l-1-5.2A4 4 0 0 0 17.3 5z"/>',
power: '<path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.8 0"/>',
grid: '<rect x="3" y="3" width="8" height="8" rx="1.5"/><rect x="13" y="3" width="8" height="8" rx="1.5"/><rect x="3" y="13" width="8" height="8" rx="1.5"/><rect x="13" y="13" width="8" height="8" rx="1.5"/>',
copy: '<rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/>',
Expand Down
Loading