import TCPHttpServer from "./tcpHttpServer"; import Logger from '@/utils/Logger'; const logger = Logger.withTag('RemoteControl'); 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) => { logger.debug("[RemoteControl] Received request:", request.method, request.url); try { if (request.method === "GET" && request.url === "/") { return { statusCode: 200, headers: { "Content-Type": "text/html; charset=utf-8" }, 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) { logger.info("[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) { logger.info("[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 { logger.debug("[RemoteControl] Attempting to start server..."); try { const url = await this.httpServer.start(); logger.debug(`[RemoteControl] Server started successfully at: ${url}`); return url; } catch (error) { logger.info("[RemoteControl] Failed to start server:", error); throw new Error(error instanceof Error ? error.message : "Failed to start server"); } } public stopServer() { logger.debug("[RemoteControl] Stopping server..."); this.httpServer.stop(); } public isRunning(): boolean { return this.httpServer.getIsRunning(); } } export const remoteControlService = new RemoteControlService();