1+ import { spawn } from '@homebridge/node-pty-prebuilt-multiarch' ;
2+ import { Router } from 'express' ;
3+
4+ import { SocketServer } from '../../socket-server.js' ;
5+
6+ export function createCommandHandler ( command : string , args ?: string ) : Router {
7+ const router = Router ( {
8+ mergeParams : true ,
9+ } ) ;
10+
11+ router . post ( '/:sessionId/start' , async ( req , res ) => {
12+ const { sessionId } = req . params ;
13+ console . log ( `Received request to ${ command } , sessionId: ${ sessionId } ` )
14+
15+ if ( ! sessionId ) {
16+ return res . status ( 400 ) . json ( { error : 'SessionId must be provided' } ) ;
17+ }
18+
19+ const server = SocketServer . get ( ) ;
20+ const socket = server . getSession ( sessionId ) ;
21+ if ( ! socket ) {
22+ return res . status ( 400 ) . json ( { error : 'SessionId does not exist' } ) ;
23+ }
24+
25+ if ( ! socket . connected ) {
26+ return res . status ( 400 ) . json ( { error : 'Socket not connected. Connect to socket before calling this endpoint' } ) ;
27+ }
28+
29+ const pty = spawn ( 'zsh' , [ '-c' , `codify ${ command } ${ args ?? '' } ` ] , {
30+ name : 'xterm-color' ,
31+ cols : 80 ,
32+ rows : 30 ,
33+ cwd : process . env . HOME ,
34+ env : process . env
35+ } ) ;
36+
37+ pty . onData ( ( data ) => {
38+ socket . emit ( 'data' , Buffer . from ( data , 'utf8' ) ) ;
39+ } ) ;
40+
41+ socket . on ( 'data' , ( message ) => {
42+ pty . write ( message . toString ( 'utf8' ) ) ;
43+ } )
44+
45+ pty . onExit ( ( { exitCode, signal } ) => {
46+ console . log ( 'pty exit' , exitCode , signal ) ;
47+ // socket.disconnect();
48+ } )
49+ } ) ;
50+
51+ return router ;
52+ }
0 commit comments