11import { IPty } from '@homebridge/node-pty-prebuilt-multiarch' ;
22import { Server as HttpServer , IncomingMessage } from 'node:http' ;
33import { Duplex } from 'node:stream' ;
4+ import { v4 as uuid } from 'uuid' ;
45import WebSocket , { WebSocketServer } from 'ws' ;
56
67import { config } from '../config.js' ;
78
89export interface Session {
910 server : WebSocketServer ;
11+ clientId : string ;
1012 ws ?: WebSocket ;
1113 pty ?: IPty ;
1214 additionalData : Record < string , unknown > ;
@@ -23,7 +25,8 @@ export class SocketServer {
2325
2426 private server : HttpServer ;
2527 private connectionSecret : string ;
26- private sessions = new Map < string , Session > ( )
28+ private mainConnections = new Map < string , WebSocket > ( ) ; // These are per webpage
29+ private sessions = new Map < string , Session > ( ) ;
2730
2831 static init ( server : HttpServer , connectionSecret : string ) : SocketServer {
2932 instance = new SocketServer ( server , connectionSecret ) ;
@@ -45,11 +48,19 @@ export class SocketServer {
4548 this . server . on ( 'upgrade' , this . onUpgrade ) ;
4649 }
4750
48- addSession ( id : string ) : void {
51+ getMainConnection ( id : string ) : WebSocket | undefined {
52+ return this . mainConnections . get ( id ) ;
53+ }
54+
55+ createSession ( clientId : string ) : string {
56+ const sessionId = uuid ( ) ;
57+
4958 this . sessions . set (
50- id ,
51- { server : this . createWssServer ( ) , additionalData : { } }
59+ sessionId ,
60+ { server : this . createWssServer ( ) , clientId , additionalData : { } }
5261 )
62+
63+ return sessionId ;
5364 }
5465
5566 removeSession ( id : string ) {
@@ -79,7 +90,7 @@ export class SocketServer {
7990 if ( pathname === '/ws' ) {
8091 console . log ( 'Client connected!' )
8192 const wss = this . createWssServer ( ) ;
82- wss . handleUpgrade ( request , socket , head , ( ws : WebSocket ) => { } ) ;
93+ wss . handleUpgrade ( request , socket , head , this . handleClientConnected ) ;
8394 }
8495
8596 const pathSections = pathname . split ( '/' ) . filter ( Boolean ) ;
@@ -110,6 +121,16 @@ export class SocketServer {
110121 }
111122 }
112123
124+ private handleClientConnected = ( ws : WebSocket ) => {
125+ const clientId = uuid ( ) ;
126+ this . mainConnections . set ( clientId , ws ) ;
127+ ws . send ( JSON . stringify ( { key : 'opened' , data : { clientId : uuid } } ) )
128+
129+ ws . on ( 'close' , ( ) => {
130+ this . mainConnections . delete ( clientId ) ;
131+ } )
132+ }
133+
113134 private validateOrigin = ( origin : string ) : boolean =>
114135 config . corsAllowedOrigins . includes ( origin )
115136
0 commit comments