-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
201 lines (166 loc) · 5.82 KB
/
server.js
File metadata and controls
201 lines (166 loc) · 5.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import express from 'express';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import cors from 'cors';
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { RealtimeHandler } from './realtime-handler.js';
// Load environment variables
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });
// Initialize Realtime Handler
const realtimeHandler = new RealtimeHandler(process.env.OPENAI_API_KEY);
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static(join(__dirname, 'public')));
// Store active connections
const connections = new Map();
// WebSocket connection handler
wss.on('connection', (ws) => {
const connectionId = generateId();
connections.set(connectionId, ws);
console.log(`New WebSocket connection: ${connectionId}`);
ws.on('message', async (message) => {
try {
const data = JSON.parse(message);
await handleMessage(ws, data, connectionId);
} catch (error) {
console.error('Error handling message:', error);
ws.send(JSON.stringify({ type: 'error', message: 'Failed to process message' }));
}
});
ws.on('close', () => {
connections.delete(connectionId);
realtimeHandler.closeSession(connectionId);
console.log(`WebSocket connection closed: ${connectionId}`);
});
// Send initial connection confirmation
ws.send(JSON.stringify({
type: 'connected',
connectionId,
message: 'Connected to Stacy AI Safety Companion'
}));
});
// Message handler for different types of WebSocket messages
async function handleMessage(ws, data, connectionId) {
const { type, payload } = data;
switch (type) {
case 'start_conversation':
await startRealtimeConversation(ws, connectionId);
break;
case 'audio_data':
// Handle audio data from client
await processAudioData(ws, payload, connectionId);
break;
case 'end_conversation':
await endConversation(ws, connectionId);
break;
case 'emergency_trigger':
await handleEmergencyTrigger(ws, payload, connectionId);
break;
default:
ws.send(JSON.stringify({ type: 'error', message: 'Unknown message type' }));
}
}
// Start a real-time conversation with OpenAI
async function startRealtimeConversation(ws, connectionId) {
try {
// Create a new realtime session
const session = await realtimeHandler.createSession(connectionId, ws);
ws.send(JSON.stringify({
type: 'conversation_started',
message: 'Hi, I\'m Stacy. I\'m here to help keep you safe. What\'s going on?'
}));
console.log(`Started realtime conversation for connection: ${connectionId}`);
} catch (error) {
console.error('Error starting conversation:', error);
ws.send(JSON.stringify({ type: 'error', message: 'Failed to start conversation' }));
}
}
// Process audio data and interact with OpenAI Realtime API
async function processAudioData(ws, payload, connectionId) {
try {
console.log(`Processing audio data for connection: ${connectionId}`);
// Send audio data to OpenAI Realtime API
if (payload.audio) {
realtimeHandler.sendAudioToOpenAI(connectionId, payload.audio);
}
// The response will come back through the realtime handler's message handling
} catch (error) {
console.error('Error processing audio:', error);
ws.send(JSON.stringify({ type: 'error', message: 'Failed to process audio' }));
}
}
// Handle emergency trigger
async function handleEmergencyTrigger(ws, payload, connectionId) {
try {
const { location, emergencyType, contactInfo } = payload;
console.log(`Emergency triggered for connection: ${connectionId}`, {
location,
emergencyType,
contactInfo
});
// This is where we'd integrate with Twilio for SMS
// For now, just acknowledge the trigger
ws.send(JSON.stringify({
type: 'emergency_acknowledged',
message: 'Emergency services have been notified. Stay calm and follow my guidance.',
actions: [
'Location shared with emergency contact',
'Routing to nearest safe location',
'Emergency services alerted'
]
}));
} catch (error) {
console.error('Error handling emergency:', error);
ws.send(JSON.stringify({ type: 'error', message: 'Failed to handle emergency' }));
}
}
// End conversation
async function endConversation(ws, connectionId) {
ws.send(JSON.stringify({
type: 'conversation_ended',
message: 'Stay safe. I\'m here whenever you need me.'
}));
console.log(`Ended conversation for connection: ${connectionId}`);
}
// Utility function to generate unique IDs
function generateId() {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
// API Routes
app.get('/', (req, res) => {
res.sendFile(join(__dirname, 'public', 'index.html'));
});
app.get('/health', (req, res) => {
const stats = realtimeHandler.getSessionStats();
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
websocketConnections: connections.size,
realtimeSessions: stats.activeSessions
});
});
app.get('/api/stats', (req, res) => {
const stats = realtimeHandler.getSessionStats();
res.json({
websocketConnections: connections.size,
realtimeSessions: stats.activeSessions,
sessions: stats.sessions,
uptime: process.uptime(),
timestamp: new Date().toISOString()
});
});
// Start server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`🚀 Stacy AI Safety Companion server running on port ${PORT}`);
console.log(`📱 Open http://localhost:${PORT} to access the app`);
});
export default app;