import TCPHttpServer from './tcpHttpServer'; const getRemotePageHTML = () => { return ` OrionTV Remote

向电视发送文本

`; }; class RemoteControlService { private httpServer: TCPHttpServer; private onMessage: (message: string) => void = () => {}; private onHandshake: () => void = () => {}; constructor() { this.httpServer = new TCPHttpServer(); this.setupRequestHandler(); } private setupRequestHandler() { this.httpServer.setRequestHandler((request) => { console.log('[RemoteControl] Received request:', request.method, request.url); try { if (request.method === 'GET' && request.url === '/') { return { statusCode: 200, headers: { 'Content-Type': 'text/html' }, body: getRemotePageHTML() }; } else if (request.method === 'POST' && request.url === '/message') { try { const parsedBody = JSON.parse(request.body || '{}'); const message = parsedBody.message; if (message) { this.onMessage(message); } return { statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'ok' }) }; } catch (parseError) { console.error('[RemoteControl] Failed to parse message body:', parseError); return { statusCode: 400, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ error: 'Invalid JSON' }) }; } } else if (request.method === 'POST' && request.url === '/handshake') { this.onHandshake(); return { statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status: 'ok' }) }; } else { return { statusCode: 404, headers: { 'Content-Type': 'text/plain' }, body: 'Not Found' }; } } catch (error) { console.error('[RemoteControl] Request handler error:', error); return { statusCode: 500, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ error: 'Internal Server Error' }) }; } }); } public init(actions: { onMessage: (message: string) => void; onHandshake: () => void }) { this.onMessage = actions.onMessage; this.onHandshake = actions.onHandshake; } public async startServer(): Promise { console.log('[RemoteControl] Attempting to start server...'); try { const url = await this.httpServer.start(); console.log(`[RemoteControl] Server started successfully at: ${url}`); return url; } catch (error) { console.error('[RemoteControl] Failed to start server:', error); throw new Error(error instanceof Error ? error.message : 'Failed to start server'); } } public stopServer() { console.log('[RemoteControl] Stopping server...'); this.httpServer.stop(); } public isRunning(): boolean { return this.httpServer.getIsRunning(); } } export const remoteControlService = new RemoteControlService();