summaryrefslogtreecommitdiff
path: root/websocket-server/src/server.ts
diff options
context:
space:
mode:
authorIlan Bigio <ilan@openai.com>2024-12-16 13:06:08 -0800
committerIlan Bigio <ilan@openai.com>2024-12-19 16:08:22 -0500
commit20009aed53d8864c9204d43a17895168a777d2cc (patch)
tree754dded819869bc34a8a2a02c66ea72dac1ccd24 /websocket-server/src/server.ts
Initial commit
Diffstat (limited to 'websocket-server/src/server.ts')
-rw-r--r--websocket-server/src/server.ts77
1 files changed, 77 insertions, 0 deletions
diff --git a/websocket-server/src/server.ts b/websocket-server/src/server.ts
new file mode 100644
index 0000000..8ab3ea6
--- /dev/null
+++ b/websocket-server/src/server.ts
@@ -0,0 +1,77 @@
+import express from "express";
+import { WebSocketServer, WebSocket } from "ws";
+import { IncomingMessage } from "http";
+import dotenv from "dotenv";
+import http from "http";
+import { readFileSync } from "fs";
+import { join } from "path";
+import cors from "cors";
+import {
+ handleCallConnection,
+ handleFrontendConnection,
+} from "./sessionManager";
+import functions from "./functionHandlers";
+
+dotenv.config();
+
+const PORT = parseInt(process.env.PORT || "8081", 10);
+const PUBLIC_URL = process.env.PUBLIC_URL || "";
+
+const app = express();
+app.use(cors());
+const server = http.createServer(app);
+const wss = new WebSocketServer({ server });
+
+app.use(express.urlencoded({ extended: false }));
+
+const twimlPath = join(__dirname, "twiml.xml");
+const twimlTemplate = readFileSync(twimlPath, "utf-8");
+
+app.get("/public-url", (req, res) => {
+ res.json({ publicUrl: PUBLIC_URL });
+});
+
+app.all("/twiml", (req, res) => {
+ const wsUrl = new URL(PUBLIC_URL);
+ wsUrl.protocol = "wss:";
+ wsUrl.pathname = `/call`;
+
+ const twimlContent = twimlTemplate.replace("{{WS_URL}}", wsUrl.toString());
+ res.type("text/xml").send(twimlContent);
+});
+
+// New endpoint to list available tools (schemas)
+app.get("/tools", (req, res) => {
+ res.json(functions.map((f) => f.schema));
+});
+
+let currentCall: WebSocket | null = null;
+let currentLogs: WebSocket | null = null;
+
+wss.on("connection", (ws: WebSocket, req: IncomingMessage) => {
+ const url = new URL(req.url || "", `http://${req.headers.host}`);
+ const parts = url.pathname.split("/").filter(Boolean);
+
+ if (parts.length < 1) {
+ ws.close();
+ return;
+ }
+
+ const type = parts[0];
+
+ if (type === "call") {
+ if (currentCall) currentCall.close();
+ currentCall = ws;
+ handleCallConnection(currentCall);
+ } else if (type === "logs") {
+ if (currentLogs) currentLogs.close();
+ currentLogs = ws;
+ handleFrontendConnection(currentLogs);
+ } else {
+ ws.close();
+ }
+});
+
+server.listen(PORT, () => {
+ console.log(`Server running on http://localhost:${PORT}`);
+});