From da782dec7fa5f5b48dee82907785150e9dec95af Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:21:03 +0100 Subject: [PATCH 1/5] =?UTF-8?q?Puestos:=20asignaci=C3=B3n=20de=20dispositi?= =?UTF-8?q?vos=20m=C3=A1s=20fiable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mandos (HidHide): - Un mando arrancado que cambia de sesión destino (puesto encendido o apagado, otra consola) se reinicia siempre: HidHide no revoca handles y la sesión anterior lo seguía leyendo (entrada doble en Steam o el juego). - Si cambia la sesión de Windows de un puesto encendido, sus mandos la siguen al momento en vez de esperar al rescan de 30 s. - Se comprueba que HidHide.sys tenga el jail de sesión (1.4.181+); si no, aviso en el log y en la tarjeta del puesto. Teclado y ratón (WinUSB): - El registro de capturas guarda la clase y el INF originales; al soltar se reinstala el driver del fabricante si lo tenía, y si no input.inf. - Si la instalación de WinUSB falla tras cambiar la clase, se devuelve la clase: el nodo ya no queda sin driver y sin anotar. - Un dispositivo que quedó capturado y estaba desenchufado al arrancar el servicio vuelve a su driver en cuanto se conecta (antes la consola se quedaba sin él hasta el siguiente arranque). Panel y log: los dispositivos asignados a un puerto vacío salen marcados como desconectados y se avisa al encender el puesto. Co-Authored-By: Claude Opus 5.5 --- Core/Api/SeatEndpoints.cs | 12 +- Core/Helpers/DeviceTopology.cs | 25 +++ Core/wwwroot/locales/bg.json | 1 + Core/wwwroot/locales/cs.json | 1 + Core/wwwroot/locales/de.json | 1 + Core/wwwroot/locales/en.json | 1 + Core/wwwroot/locales/en_GB.json | 1 + Core/wwwroot/locales/en_US.json | 1 + Core/wwwroot/locales/es.json | 1 + Core/wwwroot/locales/fr.json | 1 + Core/wwwroot/locales/hu.json | 1 + Core/wwwroot/locales/it.json | 1 + Core/wwwroot/locales/ja.json | 1 + Core/wwwroot/locales/ko.json | 1 + Core/wwwroot/locales/pl.json | 1 + Core/wwwroot/locales/pt.json | 1 + Core/wwwroot/locales/pt_BR.json | 1 + Core/wwwroot/locales/ru.json | 1 + Core/wwwroot/locales/sv.json | 1 + Core/wwwroot/locales/tr.json | 1 + Core/wwwroot/locales/uk.json | 1 + Core/wwwroot/locales/vi.json | 1 + Core/wwwroot/locales/zh.json | 1 + Core/wwwroot/locales/zh_TW.json | 1 + Core/wwwroot/seats.js | 14 +- Core/wwwroot/style.css | 2 + Services/Gamepad/GamepadSessionIsolation.cs | 41 +++- Services/Gamepad/HidHide.cs | 16 ++ Services/Seats/SeatManager.cs | 39 ++++ Services/Seats/SeatUsbCapture.cs | 205 ++++++++++++++++---- 30 files changed, 322 insertions(+), 54 deletions(-) diff --git a/Core/Api/SeatEndpoints.cs b/Core/Api/SeatEndpoints.cs index c954185..99fff0e 100644 --- a/Core/Api/SeatEndpoints.cs +++ b/Core/Api/SeatEndpoints.cs @@ -6,13 +6,15 @@ 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). +public record SeatDeviceDto(SeatDeviceKind Kind, string UsbPort, string Label, bool Present = true); 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 +139,10 @@ 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))).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/Helpers/DeviceTopology.cs b/Core/Helpers/DeviceTopology.cs index 9445e1b..5a8933f 100644 --- a/Core/Helpers/DeviceTopology.cs +++ b/Core/Helpers/DeviceTopology.cs @@ -44,6 +44,31 @@ void Add(IEnumerable ids, SeatDeviceKind kind) return result; } + 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; diff --git a/Core/wwwroot/locales/bg.json b/Core/wwwroot/locales/bg.json index cb7e5cb..754a77c 100644 --- a/Core/wwwroot/locales/bg.json +++ b/Core/wwwroot/locales/bg.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Присвоено от USB порт: ако смените устройството на този порт, то остава в работната станция.", "seat.deviceMissing": "прекъснат", "seat.noInputWarning": "Без клавиатура, мишка или геймпад работната станция ще показва само картината.", + "seat.gamepadsNotIsolated": "HidHide не е инсталиран или не може да изолира по сесия: геймпадовете на тази работна станция се виждат във всички сесии. Инсталирайте HidHide 1.4.181 или по-нова версия.", "seat.created": "Създадена работна станция \"{name}\".", "seat.saved": "Работна станция \"{name}\" е запазена", "btn.cancel": "Отказ", diff --git a/Core/wwwroot/locales/cs.json b/Core/wwwroot/locales/cs.json index 554bc6c..a43188c 100644 --- a/Core/wwwroot/locales/cs.json +++ b/Core/wwwroot/locales/cs.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Přiděleno portem USB: pokud zařízení vyměníte na tomto portu, zůstane v pracovní stanici.", "seat.deviceMissing": "odpojeno", "seat.noInputWarning": "Bez klávesnice, myši nebo gamepadu bude pracovní stanice zobrazovat pouze obraz.", + "seat.gamepadsNotIsolated": "HidHide není nainstalován nebo neumí izolovat podle relace: gamepady této pracovní stanice jsou vidět ve všech relacích. Nainstalujte HidHide 1.4.181 nebo novější.", "seat.created": "Pracovní stanice „{name}“ vytvořena", "seat.saved": "Pracovní stanice „{name}“ uložena", "btn.cancel": "Zrušit", diff --git a/Core/wwwroot/locales/de.json b/Core/wwwroot/locales/de.json index 6bab525..1fce092 100644 --- a/Core/wwwroot/locales/de.json +++ b/Core/wwwroot/locales/de.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Zugewiesen durch USB-Port: Wenn Sie das Gerät an diesem Port austauschen, bleibt es in der Workstation.", "seat.deviceMissing": "abgeschaltet", "seat.noInputWarning": "Ohne Tastatur, Maus oder Gamepad zeigt die Workstation nur das Bild an.", + "seat.gamepadsNotIsolated": "HidHide ist nicht installiert oder kann nicht pro Sitzung isolieren: Die Gamepads dieser Workstation sind in allen Sitzungen sichtbar. Installiere HidHide 1.4.181 oder neuer.", "seat.created": "Arbeitsplatz „{name}“ erstellt", "seat.saved": "Arbeitsplatz „{name}“ gespeichert", "btn.cancel": "Abbrechen", diff --git a/Core/wwwroot/locales/en.json b/Core/wwwroot/locales/en.json index c858ab0..d768774 100644 --- a/Core/wwwroot/locales/en.json +++ b/Core/wwwroot/locales/en.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Assigned by USB port: if you swap the device on that port, it stays in the seat.", "seat.deviceMissing": "disconnected", "seat.noInputWarning": "Without a keyboard, mouse or gamepad the seat will only show the picture.", + "seat.gamepadsNotIsolated": "HidHide is not installed or cannot isolate per session: this seat's gamepads are visible in every session. Install HidHide 1.4.181 or later.", "seat.created": "Seat \"{name}\" created", "seat.saved": "Seat \"{name}\" saved", "btn.cancel": "Cancel", diff --git a/Core/wwwroot/locales/en_GB.json b/Core/wwwroot/locales/en_GB.json index b8e9aef..b320fd9 100644 --- a/Core/wwwroot/locales/en_GB.json +++ b/Core/wwwroot/locales/en_GB.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Assigned by USB port: if you swap the device on that port, it stays in the seat.", "seat.deviceMissing": "disconnected", "seat.noInputWarning": "Without a keyboard, mouse or gamepad the seat will only show the picture.", + "seat.gamepadsNotIsolated": "HidHide is not installed or cannot isolate per session: this seat's gamepads are visible in every session. Install HidHide 1.4.181 or later.", "seat.created": "Seat \"{name}\" created", "seat.saved": "Seat \"{name}\" saved", "btn.cancel": "Cancel", diff --git a/Core/wwwroot/locales/en_US.json b/Core/wwwroot/locales/en_US.json index 0bbe5d6..00a0f7c 100644 --- a/Core/wwwroot/locales/en_US.json +++ b/Core/wwwroot/locales/en_US.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Assigned by USB port: if you swap the device on that port, it stays in the seat.", "seat.deviceMissing": "disconnected", "seat.noInputWarning": "Without a keyboard, mouse or gamepad the seat will only show the picture.", + "seat.gamepadsNotIsolated": "HidHide is not installed or cannot isolate per session: this seat's gamepads are visible in every session. Install HidHide 1.4.181 or later.", "seat.created": "Seat \"{name}\" created", "seat.saved": "Seat \"{name}\" saved", "btn.cancel": "Cancel", diff --git a/Core/wwwroot/locales/es.json b/Core/wwwroot/locales/es.json index e4ec689..4bf6980 100644 --- a/Core/wwwroot/locales/es.json +++ b/Core/wwwroot/locales/es.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Se asignan por puerto USB: si cambias el aparato de ese puerto, sigue en el puesto.", "seat.deviceMissing": "desconectado", "seat.noInputWarning": "Sin teclado, ratón ni mando el puesto solo mostrará la imagen.", + "seat.gamepadsNotIsolated": "HidHide no está instalado o no aísla por sesión: los mandos de este puesto se ven en todas las sesiones. Instala HidHide 1.4.181 o posterior.", "seat.created": "Puesto \"{name}\" creado", "seat.saved": "Puesto \"{name}\" guardado", "btn.cancel": "Cancelar", diff --git a/Core/wwwroot/locales/fr.json b/Core/wwwroot/locales/fr.json index a0d5ac8..3807dc7 100644 --- a/Core/wwwroot/locales/fr.json +++ b/Core/wwwroot/locales/fr.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Affectés par port USB : si vous changez l'appareil de ce port, il reste dans le poste.", "seat.deviceMissing": "déconnecté", "seat.noInputWarning": "Sans clavier, souris ni manette, le poste n'affichera que l'image.", + "seat.gamepadsNotIsolated": "HidHide n'est pas installé ou ne peut pas isoler par session : les manettes de ce poste sont visibles dans toutes les sessions. Installez HidHide 1.4.181 ou une version ultérieure.", "seat.created": "Poste « {name} » créé", "seat.saved": "Poste « {name} » enregistré", "btn.cancel": "Annuler", diff --git a/Core/wwwroot/locales/hu.json b/Core/wwwroot/locales/hu.json index ba99a28..f532fb6 100644 --- a/Core/wwwroot/locales/hu.json +++ b/Core/wwwroot/locales/hu.json @@ -133,6 +133,7 @@ "seat.devicesHint": "USB port hozzárendelve: ha ezen a porton cseréli ki az eszközt, az a munkaállomáson marad.", "seat.deviceMissing": "lekapcsolva", "seat.noInputWarning": "Billentyűzet, egér vagy gamepad nélkül a munkaállomás csak a képet mutatja.", + "seat.gamepadsNotIsolated": "A HidHide nincs telepítve, vagy nem tud munkamenetenként elkülöníteni: a munkaállomás gamepadjei minden munkamenetben láthatók. Telepítse a HidHide 1.4.181-es vagy újabb verzióját.", "seat.created": "A \"{name}\" munkaállomás létrehozva", "seat.saved": "A \"{name}\" munkaállomás mentve", "btn.cancel": "Mégse", diff --git a/Core/wwwroot/locales/it.json b/Core/wwwroot/locales/it.json index 26cab9c..1614fcc 100644 --- a/Core/wwwroot/locales/it.json +++ b/Core/wwwroot/locales/it.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Assegnato dalla porta USB: se si scambia il dispositivo su quella porta, rimane nella workstation.", "seat.deviceMissing": "disconnesso", "seat.noInputWarning": "Senza tastiera, mouse o gamepad la workstation mostrerà solo l'immagine.", + "seat.gamepadsNotIsolated": "HidHide non è installato o non può isolare per sessione: i gamepad di questa workstation sono visibili in tutte le sessioni. Installa HidHide 1.4.181 o successivo.", "seat.created": "Postazione di lavoro \"{name}\" creata", "seat.saved": "Postazione di lavoro \"{name}\" salvata", "btn.cancel": "Annulla", diff --git a/Core/wwwroot/locales/ja.json b/Core/wwwroot/locales/ja.json index 07ec56f..20204ba 100644 --- a/Core/wwwroot/locales/ja.json +++ b/Core/wwwroot/locales/ja.json @@ -133,6 +133,7 @@ "seat.devicesHint": "USB ポートによって割り当てられます。そのポート上のデバイスを交換しても、デバイスはワークステーションに残ります。", "seat.deviceMissing": "が切断されました", "seat.noInputWarning": "キーボード、マウス、またはゲームパッドがないと、ワークステーションには画像のみが表示されます。", + "seat.gamepadsNotIsolated": "HidHide がインストールされていないか、セッションごとに分離できません。このワークステーションのゲームパッドはすべてのセッションで見えます。HidHide 1.4.181 以降をインストールしてください。", "seat.created": "ワークステーション「{name}」が作成されました", "seat.saved": "ワークステーション「{name}」が保存されました", "btn.cancel": "キャンセル", diff --git a/Core/wwwroot/locales/ko.json b/Core/wwwroot/locales/ko.json index 315105a..62aa703 100644 --- a/Core/wwwroot/locales/ko.json +++ b/Core/wwwroot/locales/ko.json @@ -133,6 +133,7 @@ "seat.devicesHint": "USB 포트에 의해 할당됨: 해당 포트에서 장치를 교체하면 워크스테이션에 유지됩니다.", "seat.deviceMissing": "연결이 끊어졌습니다.", "seat.noInputWarning": "키보드, 마우스 또는 게임패드가 없으면 워크스테이션에는 그림만 표시됩니다.", + "seat.gamepadsNotIsolated": "HidHide가 설치되지 않았거나 세션별로 격리할 수 없습니다. 이 워크스테이션의 게임패드가 모든 세션에 표시됩니다. HidHide 1.4.181 이상을 설치하세요.", "seat.created": "워크스테이션 \"{name}\"가 생성되었습니다.", "seat.saved": "워크스테이션 \"{name}\"가 저장되었습니다.", "btn.cancel": "취소", diff --git a/Core/wwwroot/locales/pl.json b/Core/wwwroot/locales/pl.json index 2721810..809615a 100644 --- a/Core/wwwroot/locales/pl.json +++ b/Core/wwwroot/locales/pl.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Przypisane przez USB port: jeśli zamienisz urządzenie na tym porcie, pozostanie ono na stacji roboczej.", "seat.deviceMissing": "odłączony", "seat.noInputWarning": "Bez klawiatury, myszy lub gamepada stacja robocza pokaże tylko obraz.\nUtworzono", + "seat.gamepadsNotIsolated": "HidHide nie jest zainstalowany lub nie izoluje według sesji: gamepady tej stacji roboczej są widoczne we wszystkich sesjach. Zainstaluj HidHide 1.4.181 lub nowszy.", "seat.created": "Stanowisko robocze „{name}”.", "seat.saved": "Stacja robocza „{name}” zapisana", "btn.cancel": "Anuluj", diff --git a/Core/wwwroot/locales/pt.json b/Core/wwwroot/locales/pt.json index d024ef3..8d8ada1 100644 --- a/Core/wwwroot/locales/pt.json +++ b/Core/wwwroot/locales/pt.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Atribuídos por porta USB: se trocar o aparelho dessa porta, continua no posto.", "seat.deviceMissing": "desligado", "seat.noInputWarning": "Sem teclado, rato nem comando o posto só mostrará a imagem.", + "seat.gamepadsNotIsolated": "O HidHide não está instalado ou não isola por sessão: os comandos deste posto são visíveis em todas as sessões. Instale o HidHide 1.4.181 ou posterior.", "seat.created": "Posto \"{name}\" criado", "seat.saved": "Posto \"{name}\" guardado", "btn.cancel": "Cancelar", diff --git a/Core/wwwroot/locales/pt_BR.json b/Core/wwwroot/locales/pt_BR.json index a96bddd..108e877 100644 --- a/Core/wwwroot/locales/pt_BR.json +++ b/Core/wwwroot/locales/pt_BR.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Atribuídos pela porta USB: se você trocar o aparelho dessa porta, ele continua no posto.", "seat.deviceMissing": "desconectado", "seat.noInputWarning": "Sem teclado, mouse nem controle o posto só mostrará a imagem.", + "seat.gamepadsNotIsolated": "O HidHide não está instalado ou não isola por sessão: os controles deste posto aparecem em todas as sessões. Instale o HidHide 1.4.181 ou posterior.", "seat.created": "Posto \"{name}\" criado", "seat.saved": "Posto \"{name}\" salvo", "btn.cancel": "Cancelar", diff --git a/Core/wwwroot/locales/ru.json b/Core/wwwroot/locales/ru.json index f2aba4a..0cd2c31 100644 --- a/Core/wwwroot/locales/ru.json +++ b/Core/wwwroot/locales/ru.json @@ -134,6 +134,7 @@ "seat.devicesHint": "Назначение по USB-порту: при замене устройства в этом порту оно остаётся за рабочим местом.", "seat.deviceMissing": "отключено", "seat.noInputWarning": "Без клавиатуры, мыши или геймпада рабочее место сможет только показывать изображение.", + "seat.gamepadsNotIsolated": "HidHide не установлен или не умеет изолировать по сеансам: геймпады этого рабочего места видны во всех сеансах. Установите HidHide 1.4.181 или новее.", "seat.created": "Рабочее место «{name}» создано", "seat.saved": "Рабочее место «{name}» сохранено", "btn.cancel": "Отмена", diff --git a/Core/wwwroot/locales/sv.json b/Core/wwwroot/locales/sv.json index a350993..8f84447 100644 --- a/Core/wwwroot/locales/sv.json +++ b/Core/wwwroot/locales/sv.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Tilldelad av USB-port: om du byter enheten på den porten stannar den kvar på arbetsstationen.", "seat.deviceMissing": "kopplad", "seat.noInputWarning": "Utan tangentbord, mus eller gamepad visar arbetsstationen bara bilden.", + "seat.gamepadsNotIsolated": "HidHide är inte installerat eller kan inte isolera per session: arbetsstationens gamepads syns i alla sessioner. Installera HidHide 1.4.181 eller senare.", "seat.created": "Arbetsstationen \"{name}\" skapad", "seat.saved": "Arbetsstationen \"{name}\" har sparats", "btn.cancel": "Avbryt", diff --git a/Core/wwwroot/locales/tr.json b/Core/wwwroot/locales/tr.json index 936ef86..bef7fe6 100644 --- a/Core/wwwroot/locales/tr.json +++ b/Core/wwwroot/locales/tr.json @@ -133,6 +133,7 @@ "seat.devicesHint": "USB bağlantı noktası tarafından atanır: aygıtı bu bağlantı noktasında değiştirirseniz iş istasyonunda kalır.", "seat.deviceMissing": "'nin bağlantısı kesildi", "seat.noInputWarning": "Klavye, fare veya gamepad olmadan iş istasyonu yalnızca resmi gösterecektir.", + "seat.gamepadsNotIsolated": "HidHide yüklü değil veya oturum başına yalıtım yapamıyor: bu iş istasyonunun gamepadleri tüm oturumlarda görünüyor. HidHide 1.4.181 veya üzerini yükleyin.", "seat.created": "İş İstasyonu \"{name}\" oluşturuldu", "seat.saved": "İş İstasyonu \"{name}\" kaydedildi", "btn.cancel": "İptal", diff --git a/Core/wwwroot/locales/uk.json b/Core/wwwroot/locales/uk.json index 6c5339a..13b4468 100644 --- a/Core/wwwroot/locales/uk.json +++ b/Core/wwwroot/locales/uk.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Призначено портом USB: якщо ви поміняєте пристрій на цей порт, він залишається на робочій станції.", "seat.deviceMissing": "відключено", "seat.noInputWarning": "Без клавіатури, миші чи геймпада робоча станція показуватиме лише зображення.", + "seat.gamepadsNotIsolated": "HidHide не встановлено або він не ізолює за сеансами: геймпади цієї робочої станції видно в усіх сеансах. Встановіть HidHide 1.4.181 або новіший.", "seat.created": "Створено робочу станцію «{name}».", "seat.saved": "Робоча станція \"{name}\" збережена", "btn.cancel": "Скасувати", diff --git a/Core/wwwroot/locales/vi.json b/Core/wwwroot/locales/vi.json index 291e035..3771bc6 100644 --- a/Core/wwwroot/locales/vi.json +++ b/Core/wwwroot/locales/vi.json @@ -133,6 +133,7 @@ "seat.devicesHint": "Được gán bởi cổng USB: nếu bạn đổi thiết bị trên cổng đó, nó vẫn ở trong máy trạm.", "seat.deviceMissing": "bị ngắt kết nối", "seat.noInputWarning": "Nếu không có bàn phím, chuột hoặc gamepad thì máy trạm sẽ chỉ hiển thị hình ảnh.", + "seat.gamepadsNotIsolated": "HidHide chưa được cài đặt hoặc không thể cách ly theo phiên: gamepad của máy trạm này hiển thị trong mọi phiên. Hãy cài HidHide 1.4.181 trở lên.", "seat.created": "Máy trạm \"{name}\" đã được tạo\nĐã lưu", "seat.saved": "Máy trạm \"{name}\"", "btn.cancel": "Hủy", diff --git a/Core/wwwroot/locales/zh.json b/Core/wwwroot/locales/zh.json index f013530..f6bd0e2 100644 --- a/Core/wwwroot/locales/zh.json +++ b/Core/wwwroot/locales/zh.json @@ -133,6 +133,7 @@ "seat.devicesHint": "由 USB 端口分配:如果您交换该端口上的设备,它会保留在工作站中。", "seat.deviceMissing": "已断开", "seat.noInputWarning": "如果没有键盘、鼠标或游戏手柄,工作站将仅显示图片。\n创建", + "seat.gamepadsNotIsolated": "未安装 HidHide 或其无法按会话隔离:此工作站的游戏手柄在所有会话中可见。请安装 HidHide 1.4.181 或更高版本。", "seat.created": "工作站“{name}”", "seat.saved": "工作站“{name}”已保存", "btn.cancel": "取消", diff --git a/Core/wwwroot/locales/zh_TW.json b/Core/wwwroot/locales/zh_TW.json index acb27ea..2e5a100 100644 --- a/Core/wwwroot/locales/zh_TW.json +++ b/Core/wwwroot/locales/zh_TW.json @@ -133,6 +133,7 @@ "seat.devicesHint": "由 USB 連接埠指派:如果您交換該連接埠上的設備,它會保留在工作站中。", "seat.deviceMissing": "已斷開", "seat.noInputWarning": "如果沒有鍵盤、滑鼠或遊戲手柄,工作站將只顯示圖片。\n建立", + "seat.gamepadsNotIsolated": "未安裝 HidHide 或其無法依工作階段隔離:此工作站的遊戲手柄在所有工作階段中可見。請安裝 HidHide 1.4.181 或更新版本。", "seat.created": "工作站“{name}”", "seat.saved": "工作站「{name}」已儲存", "btn.cancel": "取消", diff --git a/Core/wwwroot/seats.js b/Core/wwwroot/seats.js index 3bbc4d8..08d03f1 100644 --- a/Core/wwwroot/seats.js +++ b/Core/wwwroot/seats.js @@ -88,12 +88,14 @@ let hwDragging = false; let hwActivePorts = new Set(); // puertos USB que se acaban de pulsar (se iluminan) // Una ficha: kind = Keyboard | Mouse | Gamepad | Audio; id = puerto USB o id de la salida de audio. -function hwChip(kind, id, label, from, draggable) { +// missing: asignado a un puerto en el que ahora no hay nada (desenchufado, o el puerto cambió de ruta). +function hwChip(kind, id, label, from, draggable, missing = false) { const active = kind !== 'Audio' && hwActivePorts.has(id) ? ' hw-active' : ''; + const gone = missing ? ' hw-missing' : ''; return ` - + title="${esc(t(kind === 'Audio' ? 'seat.audioLabel' : 'seat.kind.' + kind))}: ${esc(label)}${missing ? ` (${esc(t('seat.deviceMissing'))})` : ''}"> ${seatIcon(kind)}${esc(label)} `; } @@ -109,7 +111,7 @@ function renderSeatHardware(s, locked) { const chips = [ ...(s.audioOutId ? [hwChip('Audio', s.audioOutId, s.audioOutName || s.audioOutId, s.id, !locked)] : []), ...(s.audioInId ? [micChip(s)] : []), - ...SEAT_KINDS.flatMap(k => s.devices.filter(d => d.kind === k).map(d => hwChip(k, d.usbPort, d.label, s.id, !locked))), + ...SEAT_KINDS.flatMap(k => s.devices.filter(d => d.kind === k).map(d => hwChip(k, d.usbPort, d.label, s.id, !locked, d.present === false))), ]; return `
${esc(warning)}
`; const noInput = !s.devices.some(d => SEAT_KINDS.includes(d.kind)) ? `
${esc(t('seat.noInputWarning'))}
` : ''; + // Mandos asignados pero HidHide no los aísla (no instalado o sin "jail" de sesión): se verían en todas las sesiones. + const padsShared = s.gamepadsIsolated === false && s.devices.some(d => d.kind === 'Gamepad') + ? `
${esc(t('seat.gamepadsNotIsolated'))}
` : ''; const power = starting ? `` @@ -424,6 +429,7 @@ function renderSeatCard(s) { ${(starting || s.state === 'Stopped') && s.statusDetail ? `
${esc(I18n.status(s.statusDetail))}
` : ''} ${warning} ${noInput} + ${padsShared} ${s.errorMessage ? `
${esc(I18n.message(s.errorMessage))}
` : ''} `; else if (warning) warning = `
${esc(warning)}
`; - const noInput = !s.devices.some(d => SEAT_KINDS.includes(d.kind)) + const noInput = !s.devices.some(d => ['Keyboard', 'Mouse', 'Gamepad'].includes(d.kind)) ? `
${esc(t('seat.noInputWarning'))}
` : ''; // Mandos asignados pero HidHide no los aísla (no instalado o sin "jail" de sesión): se verían en todas las sesiones. const padsShared = s.gamepadsIsolated === false && s.devices.some(d => d.kind === 'Gamepad') ? `
${esc(t('seat.gamepadsNotIsolated'))}
` : ''; + // Otros dispositivos que abre un servicio del sistema (disco, cámara, audio): la reserva no los aísla. + const sysOpened = s.devices.filter(d => d.kind === 'Other' && d.systemOpened).map(d => d.label); + const notIsolated = sysOpened.length + ? `
${esc(t('seat.otherNotIsolated', { devices: sysOpened.join(', ') }))}
` : ''; const power = starting ? `` @@ -430,6 +436,7 @@ function renderSeatCard(s) { ${warning} ${noInput} ${padsShared} + ${notIsolated} ${s.errorMessage ? `
${esc(I18n.message(s.errorMessage))}
` : ''} ${power} -
${protos.join('')}${sessionSeatLine(s)}${clientsChip(s)}
+
${protos.join('')}${sessionSeatLine(s)}${padsChip(s)}${clientsChip(s)}
+ ${s.gamepads && s.gamepads.length && s.gamepadsIsolated === false + ? `
${esc(t('pads.notIsolated'))}
` : ''} ${metricsSlot(s)} ${startProgress(s)} ${rdpWarning(s)} @@ -202,6 +204,7 @@ 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) }, + { icon: 'gamepad', label: t('pads.menu'), run: () => openPadsModal(s.id), disabled: s.local, hint: t('pads.localDisabled') }, { icon: 'gear', label: t('btn.settings'), run: () => openEditModal(s.id) }, { sep: true }, { icon: 'trash', label: t('btn.delete'), run: () => deleteSession(s.id, s.name), danger: true, disabled: running || busy }, @@ -217,6 +220,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); @@ -1307,6 +1361,7 @@ async function powerAction(kind) { // Iconos de trazo (heredan el color del texto). const UI_ICONS = { + gamepad: '', power: '', copy: '', download: '', diff --git a/Core/wwwroot/index.html b/Core/wwwroot/index.html index 3c68634..1ae2df2 100644 --- a/Core/wwwroot/index.html +++ b/Core/wwwroot/index.html @@ -611,6 +611,24 @@

+ + +