-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
501 lines (435 loc) · 14.7 KB
/
Copy pathserver.js
File metadata and controls
501 lines (435 loc) · 14.7 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import express from 'express';
import { WebSocketServer } from 'ws';
import { createServer } from 'http';
import path from 'path';
import fs from 'fs';
import os from 'os';
import { fileURLToPath } from 'url';
import * as Y from 'yjs';
import { docs, setupWSConnection } from 'y-websocket/bin/utils';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });
// Serve static files
app.use(express.static('.'));
// Add JSON bodt parser
app.use(express.json());
// Gemini endpoint
app.post('/api/gemini', async (req, res) => {
try {
const { prompt, history = [] } = req.body;
if (!prompt) {
return res.status(400).json({ error: 'Prompt is required' });
}
// Import Gemini
const { GoogleGenerativeAI } = await import("@google/generative-ai");
// Use your own API key
const genAI = new GoogleGenerativeAI("your-API-key");
// adjust the model as you wish
const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash-lite" });
// Start chat with history
const chat = model.startChat({
history: history
});
// Send message
const result = await chat.sendMessage(prompt);
const response = result.response;
const text = response.text();
res.json({ response: text });
} catch (error) {
console.error('Gemini API error:', error);
res.status(500).json({ error: 'Failed to get response from Gemini' });
}
});
const SRC_DIR = path.join(__dirname, 'projects/0423/src');
if (!fs.existsSync(SRC_DIR)) fs.mkdirSync(SRC_DIR, { recursive: true });
// Save / load named scene snapshots to disk (used by projects/0423 draw.js)
const SAVED_DIR = path.join(__dirname, 'saved');
if (!fs.existsSync(SAVED_DIR)) fs.mkdirSync(SAVED_DIR, { recursive: true });
function safeName(name) {
return String(name).replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
}
app.post('/api/save/:name', (req, res) => {
try {
let fileName = req.params.name;
if ( fileName.indexOf('.js') > 0 ||
fileName.indexOf('.cg') > 0 ||
fileName.indexOf('.fs') > 0 ) {
let file = path.join(SRC_DIR, fileName);
let str = JSON.stringify(req.body);
str = str.substring(9, str.length-3);
str = str.replaceAll("\\n", "\n");
fs.writeFileSync(file, str);
}
else {
const file = path.join(SAVED_DIR, safeName(req.params.name) + '.json');
fs.writeFileSync(file, JSON.stringify(req.body));
}
res.json({ ok: true });
} catch (err) {
console.error('save error:', err);
res.status(500).json({ error: 'save failed' });
}
});
app.get('/api/load/:name', (req, res) => {
try {
const file = path.join(SAVED_DIR, safeName(req.params.name) + '.json');
if (!fs.existsSync(file)) return res.status(404).json({ error: 'not found' });
res.json(JSON.parse(fs.readFileSync(file, 'utf8')));
} catch (err) {
console.error('load error:', err);
res.status(500).json({ error: 'load failed' });
}
});
// Mint short-lived TURN credentials via Cloudflare Realtime, so WebRTC peer connections
// can fall back to a relay when direct P2P (STUN-only) fails due to NAT/firewall (see
// WEBRTC_SETUP.md). The TURN API token stays server-side; the browser only ever
// receives a credential that expires in TURN_TTL_SECONDS.
const CF_TURN_KEY_ID = process.env.CF_TURN_KEY_ID;
const CF_TURN_API_TOKEN = process.env.CF_TURN_API_TOKEN;
const TURN_TTL_SECONDS = 4 * 60 * 60; // 4 hours - comfortably longer than any single call
app.get('/api/turn-credentials', async (req, res) => {
if (!CF_TURN_KEY_ID || !CF_TURN_API_TOKEN) {
// Not configured - client falls back to STUN-only.
return res.json({ iceServers: [] });
}
try {
const response = await fetch(
`https://rtc.live.cloudflare.com/v1/turn/keys/${CF_TURN_KEY_ID}/credentials/generate-ice-servers`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${CF_TURN_API_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ ttl: TURN_TTL_SECONDS })
}
);
if (!response.ok)
throw new Error(`Cloudflare TURN API returned ${response.status}`);
const data = await response.json();
res.json({ iceServers: data.iceServers || [] });
} catch (err) {
console.error('TURN credential fetch failed:', err);
res.json({ iceServers: [] });
}
});
// Report this machine's LAN addresses, so a web page served from here can tell
// a peer on another device how to reach this server (e.g. for the channel relay).
app.get('/api/netinfo', (req, res) => {
const ips = [];
const interfaces = os.networkInterfaces();
for (const name in interfaces)
for (const i of interfaces[name])
if (i.family === 'IPv4' && !i.internal)
ips.push(i.address);
res.json({ ips, port: PORT });
});
app.get('/api/saves', (req, res) => {
try {
const names = fs.readdirSync(SAVED_DIR)
.filter(f => f.endsWith('.json'))
.map(f => f.slice(0, -5));
res.json({ saves: names });
} catch (err) {
res.status(500).json({ error: 'list failed' });
}
});
// Endpoint to clear Yjs document cache
app.post('/api/clear-yjs-cache/:docName?', (req, res) => {
const docName = req.params.docName;
if (docName) {
const doc = docs.get(docName);
// Clear specific document
if (doc) {
doc.destroy();
docs.delete(docName);
console.log(`Cleared Yjs document: ${docName}`);
res.json({ success: true, message: `Cleared document: ${docName}` });
} else {
res.json({ success: false, message: `Document not found: ${docName}` });
}
} else {
// Clear all documents
const count = docs.size;
docs.clear();
console.log(`Cleared all ${count} Yjs documents`);
res.json({ success: true, message: `Cleared ${count} documents` });
}
});
// GET endpoint for easier browser access
app.get('/api/clear-yjs-cache/:docName?', (req, res) => {
const docName = req.params.docName;
if (docName) {
const doc = docs.get(docName);
if (doc) {
doc.destroy();
docs.delete(docName);
console.log(`Cleared Yjs document: ${docName}`);
res.send(`<h1>Cleared document: ${docName}</h1><p><a href="/">Back to BICI</a></p>`);
} else {
res.send(`<h1>Document not found: ${docName}</h1><p><a href="/">Back to BICI</a></p>`);
}
} else {
const count = docs.size;
docs.forEach((doc) => doc.destroy());
docs.clear();
console.log(`Cleared all ${count} Yjs documents`);
res.send(`<h1>Cleared ${count} documents</h1><p><a href="/">Back to BICI</a></p>`);
}
});
// Store connected clients
const clients = new Map();
// Store rooms: roomId -> { clients: Set<clientId>, createdAt: timestamp }
const rooms = new Map();
// Store client-to-room mapping: clientId -> roomId
const clientRooms = new Map();
// Generate short room code (6 alphanumeric characters)
function generateRoomCode() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let code = '';
for (let i = 0; i < 6; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
// Ensure uniqueness
return rooms.has(code) ? generateRoomCode() : code;
}
// Create a new room
function createRoom(roomId = null) {
const id = roomId || generateRoomCode();
if (!rooms.has(id)) {
rooms.set(id, {
clients: new Set(),
createdAt: Date.now()
});
console.log(`Created room: ${id}`);
}
return id;
}
// Add client to room
function addClientToRoom(clientId, roomId) {
const room = rooms.get(roomId);
if (!room) {
console.error(`Room ${roomId} does not exist`);
return false;
}
// Check room capacity (max 2 for 1-on-1)
if (room.clients.size >= 2) {
console.log(`Room ${roomId} is full (${room.clients.size}/2)`);
return false;
}
room.clients.add(clientId);
clientRooms.set(clientId, roomId);
console.log(`Client ${clientId} joined room ${roomId} (${room.clients.size}/2)`);
return true;
}
// Remove client from room and cleanup if empty
function removeClientFromRoom(clientId) {
const roomId = clientRooms.get(clientId);
if (!roomId) return;
const room = rooms.get(roomId);
if (room) {
room.clients.delete(clientId);
console.log(`Client ${clientId} left room ${roomId} (${room.clients.size}/2)`);
// Auto-delete room if empty
if (room.clients.size === 0) {
rooms.delete(roomId);
console.log(`Deleted empty room: ${roomId}`);
}
}
clientRooms.delete(clientId);
}
// Get clients in same room
function getRoomClients(roomId) {
const room = rooms.get(roomId);
return room ? Array.from(room.clients) : [];
}
// Channel relay rooms: every message from a client is forwarded verbatim to the
// other clients in its room. This is the TCP fallback for the WebRTC channel,
// for device pairs whose peer-to-peer UDP path cannot stay alive.
const relayRooms = new Map();
wss.on('connection', (ws, req) => {
// Check if this is a y-websocket connection (has docName in URL)
const url = new URL(req.url, `http://${req.headers.host}`);
const docName = url.pathname.slice(1); // Remove leading '/'
if (url.pathname === '/relay') {
const room = url.searchParams.get('room') || '';
if (!relayRooms.has(room))
relayRooms.set(room, new Set());
const peers = relayRooms.get(room);
peers.add(ws);
console.log(`Relay client joined room ${room} (${peers.size} in room)`);
ws.on('message', (message) => {
for (const other of peers)
if (other !== ws && other.readyState === 1)
other.send(message.toString());
});
ws.on('close', () => {
peers.delete(ws);
if (peers.size === 0)
relayRooms.delete(room);
});
ws.on('error', () => {});
return;
}
if (docName) {
console.log(`Yjs client connected to document: ${docName}`);
setupWSConnection(ws, req, { docName });
return
}
// Regular WebRTC signaling connection
const clientId = Math.random().toString(36).substr(2, 9);
clients.set(clientId, ws);
console.log(`Client connected: ${clientId}. Total clients: ${clients.size}`);
// Parse room ID from URL query parameters
const roomIdFromUrl = url.searchParams.get('room');
let roomId = null;
let roomJoinSuccess = false;
let roomFull = false;
if (roomIdFromUrl) {
// Client wants to join a specific room
if (!rooms.has(roomIdFromUrl)) {
// Room doesn't exist, create it
createRoom(roomIdFromUrl);
}
roomJoinSuccess = addClientToRoom(clientId, roomIdFromUrl);
if (roomJoinSuccess) {
roomId = roomIdFromUrl;
} else {
roomFull = true;
}
} else {
// No room specified, auto-create a new room
roomId = createRoom();
addClientToRoom(clientId, roomId);
roomJoinSuccess = true;
}
// Send the client their ID and room info
ws.send(JSON.stringify({
type: 'welcome',
clientId: clientId,
roomId: roomId,
roomFull: roomFull,
totalClients: clients.size
}));
if (roomJoinSuccess) {
// Broadcast updated client list to clients in the same room
broadcastClientListToRoom(roomId);
}
ws.on('message', (message) => {
try {
const data = JSON.parse(message.toString());
// Handle different message types
switch (data.type) {
case 'offer':
case 'answer':
case 'ice-candidate':
// Forward WebRTC signaling messages to the target peer
const targetClient = clients.get(data.target);
if (targetClient && targetClient.readyState === 1) {
targetClient.send(JSON.stringify({
...data,
from: clientId
}));
}
break;
case 'request-client-list':
// Send current client list to requester
sendClientList(ws, clientId);
break;
case 'state-update':
// Broadcast state updates to clients in the same room only
const senderRoomId = clientRooms.get(clientId);
if (senderRoomId) {
//console.log('Broadcasting state update from:', clientId, 'in room:', senderRoomId);
const roomClients = getRoomClients(senderRoomId);
roomClients.forEach((id) => {
if (id !== clientId) {
const client = clients.get(id);
if (client && client.readyState === 1) {
client.send(JSON.stringify({
type: 'state-update',
from: clientId,
state: data.state
}));
}
}
});
}
break;
case 'action':
// Relay action from secondary client to master client
console.log('Relaying action from:', clientId, 'to master:', data.to);
const masterClient = clients.get(data.to);
if (masterClient && masterClient.readyState === 1) {
masterClient.send(JSON.stringify({
type: 'action',
from: clientId,
action: data.action,
seq: data.seq
}));
}
break;
default:
console.log('Unknown message type:', data.type);
}
} catch (error) {
console.error('Error processing message:', error);
}
});
ws.on('close', () => {
const roomId = clientRooms.get(clientId);
clients.delete(clientId);
removeClientFromRoom(clientId);
console.log(`Client disconnected: ${clientId}. Total clients: ${clients.size}`);
// Notify other clients in the room
if (roomId) {
broadcastClientListToRoom(roomId);
}
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
});
// Broadcast client list to all clients in a specific room
function broadcastClientListToRoom(roomId) {
const roomClientIds = getRoomClients(roomId);
const message = JSON.stringify({
type: 'client-list',
clients: roomClientIds
});
roomClientIds.forEach((clientId) => {
const client = clients.get(clientId);
if (client && client.readyState === 1) { // OPEN
client.send(message);
}
});
}
// Legacy function for backwards compatibility (now uses rooms)
function broadcastClientList() {
rooms.forEach((room, roomId) => {
broadcastClientListToRoom(roomId);
});
}
function sendClientList(ws, excludeId) {
const roomId = clientRooms.get(excludeId);
if (!roomId) {
ws.send(JSON.stringify({
type: 'client-list',
clients: []
}));
return;
}
const clientIds = getRoomClients(roomId).filter(id => id !== excludeId);
ws.send(JSON.stringify({
type: 'client-list',
clients: clientIds
}));
}
const PORT = process.env.PORT || 8000;
server.listen(PORT, () => {
console.log(`🚀 BICI server running on http://localhost:${PORT}`);
console.log(`📡 WebRTC signaling server ready for connections`);
});