peerpigeon 0.0.4 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -4
- package/examples/browser/app.js +40 -39
- package/examples/browser/crypto-test.html +427 -0
- package/examples/browser/index.html +161 -0
- package/examples/browser/styles.css +216 -0
- package/examples/browser/ui-old.js +1926 -0
- package/examples/browser/ui.js +2226 -1692
- package/examples/node/test-crypto-media.js +137 -0
- package/examples/node/test-crypto.js +146 -0
- package/examples/node/test-node.js +114 -115
- package/package.json +51 -8
- package/src/CleanupManager.js +154 -154
- package/src/ConnectionManager.js +772 -749
- package/src/CryptoManager.js +612 -0
- package/src/EnvironmentDetector.js +381 -381
- package/src/EventEmitter.js +19 -19
- package/src/EvictionManager.js +211 -211
- package/src/GossipManager.js +447 -366
- package/src/MediaManager.js +218 -195
- package/src/MeshOptimizer.js +165 -166
- package/src/PeerConnection.js +850 -758
- package/src/PeerDiscovery.js +255 -259
- package/src/PeerPigeonMesh.js +1082 -723
- package/src/SignalingClient.js +517 -518
- package/src/SignalingHandler.js +295 -291
- package/src/StorageManager.js +105 -105
- package/src/TimerUtils.js +29 -29
- package/src/WebDHT.js +951 -951
- package/websocket-server/server.js +371 -332
|
@@ -0,0 +1,1926 @@
|
|
|
1
|
+
// Updated: 2025-07-04 - Fixed getConnectionStatus method name
|
|
2
|
+
export class PeerPigeonUI {
|
|
3
|
+
constructor(mesh) {
|
|
4
|
+
this.mesh = mesh;
|
|
5
|
+
this.lastCleanupTime = 0; // Track when we last did cleanup
|
|
6
|
+
this.setupEventListeners();
|
|
7
|
+
this.bindDOMEvents();
|
|
8
|
+
this.initializeMedia();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
setupEventListeners() {
|
|
12
|
+
this.mesh.addEventListener('statusChanged', (data) => {
|
|
13
|
+
this.handleStatusChange(data);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
this.mesh.addEventListener('peerDiscovered', (_data) => {
|
|
17
|
+
this.updateDiscoveredPeers();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
this.mesh.addEventListener('peerConnected', (_data) => {
|
|
21
|
+
this.updateUI();
|
|
22
|
+
this.updateDiscoveredPeers();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
this.mesh.addEventListener('peerDisconnected', (data) => {
|
|
26
|
+
this.addMessage('System', `Peer ${data.peerId.substring(0, 8)}... disconnected (${data.reason})`);
|
|
27
|
+
this.updateUI();
|
|
28
|
+
this.updateDiscoveredPeers();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
this.mesh.addEventListener('messageReceived', (data) => {
|
|
32
|
+
// Only show messages from other peers, not self
|
|
33
|
+
if (data.from !== this.mesh.peerId) {
|
|
34
|
+
if (data.direct) {
|
|
35
|
+
this.addMessage(`${data.from.substring(0, 8)}...`, `(DM) ${data.content}`, 'dm');
|
|
36
|
+
} else {
|
|
37
|
+
this.addMessage(`${data.from.substring(0, 8)}...`, data.content);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
this.mesh.addEventListener('peerEvicted', (_data) => {
|
|
43
|
+
this.updateUI();
|
|
44
|
+
this.updateDiscoveredPeers();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
this.mesh.addEventListener('peersUpdated', () => {
|
|
48
|
+
this.updateDiscoveredPeers();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
this.mesh.addEventListener('connectionStats', (_stats) => {
|
|
52
|
+
// Handle connection stats if needed
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// DHT event listeners
|
|
56
|
+
this.mesh.addEventListener('dhtValueChanged', (data) => {
|
|
57
|
+
const { key, newValue, timestamp } = data;
|
|
58
|
+
this.addDHTLogEntry(`🔔 Value Changed: ${key} = ${JSON.stringify(newValue)} (timestamp: ${timestamp})`);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// Media event listeners
|
|
62
|
+
this.mesh.addEventListener('localStreamStarted', (data) => {
|
|
63
|
+
this.handleLocalStreamStarted(data);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
this.mesh.addEventListener('localStreamStopped', () => {
|
|
67
|
+
this.handleLocalStreamStopped();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
this.mesh.addEventListener('mediaError', (data) => {
|
|
71
|
+
this.addMessage('System', `Media error: ${data.error.message}`, 'error');
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// Listen for remote streams
|
|
75
|
+
this.mesh.addEventListener('remoteStream', (data) => {
|
|
76
|
+
this.handleRemoteStream(data);
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
handleStatusChange(data) {
|
|
81
|
+
switch (data.type) {
|
|
82
|
+
case 'initialized':
|
|
83
|
+
this.updateUI();
|
|
84
|
+
break;
|
|
85
|
+
case 'connecting':
|
|
86
|
+
this.addMessage('System', 'Connecting to signaling server...');
|
|
87
|
+
this.updateUI();
|
|
88
|
+
break;
|
|
89
|
+
case 'connected':
|
|
90
|
+
this.addMessage('System', 'Connected to signaling server');
|
|
91
|
+
this.updateUI();
|
|
92
|
+
break;
|
|
93
|
+
case 'disconnected':
|
|
94
|
+
this.addMessage('System', 'Disconnected from signaling server');
|
|
95
|
+
this.updateUI();
|
|
96
|
+
this.updateDiscoveredPeers();
|
|
97
|
+
break;
|
|
98
|
+
case 'error':
|
|
99
|
+
this.addMessage('System', data.message, 'error');
|
|
100
|
+
this.updateUI();
|
|
101
|
+
break;
|
|
102
|
+
case 'warning':
|
|
103
|
+
this.addMessage('System', data.message, 'warning');
|
|
104
|
+
break;
|
|
105
|
+
case 'info':
|
|
106
|
+
this.addMessage('System', data.message);
|
|
107
|
+
break;
|
|
108
|
+
case 'urlLoaded':
|
|
109
|
+
document.getElementById('signaling-url').value = data.signalingUrl;
|
|
110
|
+
this.addMessage('System', `API Gateway URL loaded: ${data.signalingUrl}`);
|
|
111
|
+
break;
|
|
112
|
+
case 'setting': {
|
|
113
|
+
const settingName = data.setting === 'autoDiscovery'
|
|
114
|
+
? 'Auto discovery'
|
|
115
|
+
: data.setting === 'evictionStrategy'
|
|
116
|
+
? 'Smart eviction strategy'
|
|
117
|
+
: data.setting === 'xorRouting'
|
|
118
|
+
? 'XOR-based routing'
|
|
119
|
+
: data.setting === 'connectionType' ? 'Connection type' : data.setting;
|
|
120
|
+
|
|
121
|
+
if (data.setting === 'connectionType') {
|
|
122
|
+
this.addMessage('System', `${settingName} set to: ${data.value}`);
|
|
123
|
+
} else {
|
|
124
|
+
this.addMessage('System', `${settingName} ${data.value ? 'enabled' : 'disabled'}`);
|
|
125
|
+
}
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
bindDOMEvents() {
|
|
132
|
+
// Connection controls
|
|
133
|
+
document.getElementById('connect-btn').addEventListener('click', () => {
|
|
134
|
+
this.handleConnect();
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
document.getElementById('disconnect-btn').addEventListener('click', () => {
|
|
138
|
+
this.handleDisconnect();
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
document.getElementById('cleanup-btn').addEventListener('click', () => {
|
|
142
|
+
this.handleCleanup();
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
document.getElementById('health-check-btn').addEventListener('click', () => {
|
|
146
|
+
this.handleHealthCheck();
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
document.getElementById('refresh-btn').addEventListener('click', () => {
|
|
150
|
+
window.location.reload();
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// Messaging
|
|
154
|
+
document.getElementById('send-message-btn').addEventListener('click', () => {
|
|
155
|
+
this.sendMessage();
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
document.getElementById('message-input').addEventListener('keypress', (e) => {
|
|
159
|
+
if (e.key === 'Enter') {
|
|
160
|
+
this.sendMessage();
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
// Manual connection
|
|
165
|
+
document.getElementById('connect-peer-btn').addEventListener('click', () => {
|
|
166
|
+
this.connectToPeer();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
document.getElementById('target-peer').addEventListener('keypress', (e) => {
|
|
170
|
+
if (e.key === 'Enter') {
|
|
171
|
+
this.connectToPeer();
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
// Settings
|
|
176
|
+
document.getElementById('min-peers').addEventListener('change', (e) => {
|
|
177
|
+
this.mesh.setMinPeers(parseInt(e.target.value));
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
document.getElementById('max-peers').addEventListener('change', (e) => {
|
|
181
|
+
this.mesh.setMaxPeers(parseInt(e.target.value));
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
document.getElementById('auto-discovery-toggle').addEventListener('change', (e) => {
|
|
185
|
+
this.mesh.setAutoDiscovery(e.target.checked);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
document.getElementById('eviction-strategy-toggle').addEventListener('change', (e) => {
|
|
189
|
+
this.mesh.setEvictionStrategy(e.target.checked);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
document.getElementById('xor-routing-toggle').addEventListener('change', (e) => {
|
|
193
|
+
this.mesh.setXorRouting(e.target.checked);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
// DHT controls
|
|
197
|
+
this.setupDHTControls();
|
|
198
|
+
|
|
199
|
+
// Collapsible sections
|
|
200
|
+
this.setupCollapsibleSections();
|
|
201
|
+
|
|
202
|
+
// Media controls
|
|
203
|
+
this.setupMediaControls();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
setupDHTControls() {
|
|
207
|
+
// DHT input fields and controls
|
|
208
|
+
const dhtKey = document.getElementById('dht-key');
|
|
209
|
+
const dhtValue = document.getElementById('dht-value');
|
|
210
|
+
const dhtGetKey = document.getElementById('dht-get-key'); // Separate key field for retrieval
|
|
211
|
+
const dhtPutBtn = document.getElementById('dht-put-btn');
|
|
212
|
+
const dhtUpdateBtn = document.getElementById('dht-update-btn');
|
|
213
|
+
const dhtGetBtn = document.getElementById('dht-get-btn');
|
|
214
|
+
const dhtSubscribeBtn = document.getElementById('dht-subscribe-btn');
|
|
215
|
+
const dhtUnsubscribeBtn = document.getElementById('dht-unsubscribe-btn');
|
|
216
|
+
const dhtEnableTtl = document.getElementById('dht-enable-ttl');
|
|
217
|
+
const dhtTtlGroup = document.getElementById('dht-ttl-group');
|
|
218
|
+
const dhtTtl = document.getElementById('dht-ttl');
|
|
219
|
+
|
|
220
|
+
// Debug: Check if elements are found
|
|
221
|
+
console.log('DHT Controls setup - Elements found:', {
|
|
222
|
+
dhtKey: !!dhtKey,
|
|
223
|
+
dhtValue: !!dhtValue,
|
|
224
|
+
dhtGetKey: !!dhtGetKey,
|
|
225
|
+
dhtPutBtn: !!dhtPutBtn,
|
|
226
|
+
dhtUpdateBtn: !!dhtUpdateBtn,
|
|
227
|
+
dhtGetBtn: !!dhtGetBtn,
|
|
228
|
+
dhtSubscribeBtn: !!dhtSubscribeBtn,
|
|
229
|
+
dhtUnsubscribeBtn: !!dhtUnsubscribeBtn
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
if (!dhtKey) {
|
|
233
|
+
console.error('DHT key input element not found!');
|
|
234
|
+
this.addDHTLogEntry('❌ Error: DHT key input field not found in DOM');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (!dhtValue) {
|
|
238
|
+
console.error('DHT value input element not found!');
|
|
239
|
+
this.addDHTLogEntry('❌ Error: DHT value input field not found in DOM');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (!dhtGetKey) {
|
|
243
|
+
console.error('DHT get-key input element not found!');
|
|
244
|
+
this.addDHTLogEntry('❌ Error: DHT get-key input field not found in DOM');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Toggle TTL input visibility
|
|
248
|
+
if (dhtEnableTtl && dhtTtlGroup) {
|
|
249
|
+
dhtEnableTtl.addEventListener('change', (e) => {
|
|
250
|
+
dhtTtlGroup.style.display = e.target.checked ? 'block' : 'none';
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Store in DHT
|
|
255
|
+
if (dhtPutBtn) {
|
|
256
|
+
dhtPutBtn.addEventListener('click', async () => {
|
|
257
|
+
const key = dhtKey?.value?.trim();
|
|
258
|
+
const value = dhtValue?.value?.trim();
|
|
259
|
+
|
|
260
|
+
// Debug logging
|
|
261
|
+
console.log('DHT PUT - Elements found:', {
|
|
262
|
+
dhtKey: !!dhtKey,
|
|
263
|
+
dhtValue: !!dhtValue,
|
|
264
|
+
keyValue: key,
|
|
265
|
+
valueValue: value
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
if (!key || !value) {
|
|
269
|
+
this.addDHTLogEntry('❌ Error: Both key and value are required');
|
|
270
|
+
this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (!this.mesh.isDHTEnabled()) {
|
|
275
|
+
this.addDHTLogEntry('❌ Error: WebDHT is disabled');
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
try {
|
|
280
|
+
let parsedValue;
|
|
281
|
+
try {
|
|
282
|
+
parsedValue = JSON.parse(value);
|
|
283
|
+
} catch {
|
|
284
|
+
parsedValue = value; // Use as string if not valid JSON
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const options = {};
|
|
288
|
+
if (dhtEnableTtl?.checked && dhtTtl?.value) {
|
|
289
|
+
options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const success = await this.mesh.dhtPut(key, parsedValue, options);
|
|
293
|
+
if (success) {
|
|
294
|
+
this.addDHTLogEntry(`✅ Stored: ${key} = ${JSON.stringify(parsedValue)}`);
|
|
295
|
+
if (options.ttl) {
|
|
296
|
+
this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
|
|
297
|
+
}
|
|
298
|
+
this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
|
|
299
|
+
|
|
300
|
+
// Auto-subscribe to the key we just stored (essential for original storing peers)
|
|
301
|
+
try {
|
|
302
|
+
await this.mesh.dhtSubscribe(key);
|
|
303
|
+
this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
|
|
304
|
+
this.addDHTLogEntry(' 📡 Will receive and relay all future updates for this key');
|
|
305
|
+
} catch (subscribeError) {
|
|
306
|
+
this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
|
|
307
|
+
}
|
|
308
|
+
} else {
|
|
309
|
+
this.addDHTLogEntry(`❌ Failed to store: ${key}`);
|
|
310
|
+
}
|
|
311
|
+
} catch (error) {
|
|
312
|
+
this.addDHTLogEntry(`❌ Error storing ${key}: ${error.message}`);
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Update in DHT
|
|
318
|
+
if (dhtUpdateBtn) {
|
|
319
|
+
dhtUpdateBtn.addEventListener('click', async () => {
|
|
320
|
+
const key = dhtKey?.value?.trim();
|
|
321
|
+
const value = dhtValue?.value?.trim();
|
|
322
|
+
|
|
323
|
+
// Debug logging
|
|
324
|
+
console.log('DHT UPDATE - Elements found:', {
|
|
325
|
+
dhtKey: !!dhtKey,
|
|
326
|
+
dhtValue: !!dhtValue,
|
|
327
|
+
keyValue: key,
|
|
328
|
+
valueValue: value
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
if (!key || !value) {
|
|
332
|
+
this.addDHTLogEntry('❌ Error: Both key and value are required');
|
|
333
|
+
this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (!this.mesh.isDHTEnabled()) {
|
|
338
|
+
this.addDHTLogEntry('❌ Error: WebDHT is disabled');
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
try {
|
|
343
|
+
let parsedValue;
|
|
344
|
+
try {
|
|
345
|
+
parsedValue = JSON.parse(value);
|
|
346
|
+
} catch {
|
|
347
|
+
parsedValue = value; // Use as string if not valid JSON
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const options = {};
|
|
351
|
+
if (dhtEnableTtl?.checked && dhtTtl?.value) {
|
|
352
|
+
options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const success = await this.mesh.dhtUpdate(key, parsedValue, options);
|
|
356
|
+
if (success) {
|
|
357
|
+
this.addDHTLogEntry(`🔄 Updated: ${key} = ${JSON.stringify(parsedValue)}`);
|
|
358
|
+
if (options.ttl) {
|
|
359
|
+
this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
|
|
360
|
+
}
|
|
361
|
+
this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
|
|
362
|
+
|
|
363
|
+
// Auto-subscribe to the key we just updated (essential for original storing peers)
|
|
364
|
+
try {
|
|
365
|
+
await this.mesh.dhtSubscribe(key);
|
|
366
|
+
this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
|
|
367
|
+
this.addDHTLogEntry(' 📡 Will receive and relay all future updates for this key');
|
|
368
|
+
} catch (subscribeError) {
|
|
369
|
+
this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
|
|
370
|
+
}
|
|
371
|
+
} else {
|
|
372
|
+
this.addDHTLogEntry(`❌ Failed to update: ${key}`);
|
|
373
|
+
}
|
|
374
|
+
} catch (error) {
|
|
375
|
+
this.addDHTLogEntry(`❌ Error updating ${key}: ${error.message}`);
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// Get from DHT
|
|
381
|
+
if (dhtGetBtn) {
|
|
382
|
+
dhtGetBtn.addEventListener('click', async () => {
|
|
383
|
+
const key = dhtGetKey?.value?.trim(); // Fixed: Use dhtGetKey instead of dhtKey
|
|
384
|
+
|
|
385
|
+
// Debug logging
|
|
386
|
+
console.log('DHT GET - Elements found:', {
|
|
387
|
+
dhtGetKey: !!dhtGetKey,
|
|
388
|
+
keyValue: key
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
if (!key) {
|
|
392
|
+
this.addDHTLogEntry('❌ Error: Key is required');
|
|
393
|
+
this.addDHTLogEntry(` Debug: key="${key}"`);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (!this.mesh.isDHTEnabled()) {
|
|
398
|
+
this.addDHTLogEntry('❌ Error: WebDHT is disabled');
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
try {
|
|
403
|
+
this.addDHTLogEntry(`🔍 Fetching from ORIGINAL STORING PEERS: ${key}`);
|
|
404
|
+
this.addDHTLogEntry(' 📡 Bypassing local cache to ensure fresh data');
|
|
405
|
+
|
|
406
|
+
// Force fresh retrieval from original storing peers
|
|
407
|
+
const value = await this.mesh.dhtGet(key, { forceRefresh: true });
|
|
408
|
+
if (value !== null) {
|
|
409
|
+
this.addDHTLogEntry(`📥 Retrieved from original peers: ${key} = ${JSON.stringify(value)}`);
|
|
410
|
+
this.addDHTLogEntry(' ✅ Data is FRESH from authoritative source');
|
|
411
|
+
if (dhtValue) {
|
|
412
|
+
dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Auto-subscribe to the key we just retrieved for future updates
|
|
416
|
+
try {
|
|
417
|
+
await this.mesh.dhtSubscribe(key);
|
|
418
|
+
this.addDHTLogEntry(`🔔 Auto-subscribed for future updates: ${key}`);
|
|
419
|
+
this.addDHTLogEntry(' 📡 Will receive notifications when original peers update this key');
|
|
420
|
+
} catch (subscribeError) {
|
|
421
|
+
this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
|
|
422
|
+
}
|
|
423
|
+
} else {
|
|
424
|
+
this.addDHTLogEntry(`❌ Not found on original storing peers: ${key}`);
|
|
425
|
+
this.addDHTLogEntry(' 💡 Key may not exist or all original storing peers are offline');
|
|
426
|
+
}
|
|
427
|
+
} catch (error) {
|
|
428
|
+
this.addDHTLogEntry(`❌ Error retrieving ${key}: ${error.message}`);
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// Subscribe to DHT key
|
|
434
|
+
if (dhtSubscribeBtn) {
|
|
435
|
+
dhtSubscribeBtn.addEventListener('click', async () => {
|
|
436
|
+
// Check both key fields - use whichever has a value
|
|
437
|
+
const putKey = dhtKey?.value?.trim();
|
|
438
|
+
const getKey = dhtGetKey?.value?.trim();
|
|
439
|
+
const key = putKey || getKey;
|
|
440
|
+
|
|
441
|
+
if (!key) {
|
|
442
|
+
this.addDHTLogEntry('❌ Error: Key is required (enter key in either Put/Update or Get field)');
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
if (!this.mesh.isDHTEnabled()) {
|
|
447
|
+
this.addDHTLogEntry('❌ Error: WebDHT is disabled');
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
try {
|
|
452
|
+
this.addDHTLogEntry(`🔔 Explicitly subscribing to key: ${key}`);
|
|
453
|
+
this.addDHTLogEntry(' 📡 Will receive notifications when original storing peers update this key');
|
|
454
|
+
|
|
455
|
+
const value = await this.mesh.dhtSubscribe(key);
|
|
456
|
+
this.addDHTLogEntry(`✅ Subscribed to: ${key}`);
|
|
457
|
+
if (value !== null) {
|
|
458
|
+
this.addDHTLogEntry(` Current value from original storing peers: ${JSON.stringify(value)}`);
|
|
459
|
+
if (dhtValue) {
|
|
460
|
+
dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
|
|
461
|
+
}
|
|
462
|
+
} else {
|
|
463
|
+
this.addDHTLogEntry(' No current value found on original storing peers');
|
|
464
|
+
}
|
|
465
|
+
} catch (error) {
|
|
466
|
+
this.addDHTLogEntry(`❌ Error subscribing to ${key}: ${error.message}`);
|
|
467
|
+
}
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// Unsubscribe from DHT key
|
|
472
|
+
if (dhtUnsubscribeBtn) {
|
|
473
|
+
dhtUnsubscribeBtn.addEventListener('click', async () => {
|
|
474
|
+
// Check both key fields - use whichever has a value
|
|
475
|
+
const putKey = dhtKey?.value?.trim();
|
|
476
|
+
const getKey = dhtGetKey?.value?.trim();
|
|
477
|
+
const key = putKey || getKey;
|
|
478
|
+
|
|
479
|
+
if (!key) {
|
|
480
|
+
this.addDHTLogEntry('❌ Error: Key is required (enter key in either Put/Update or Get field)');
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
if (!this.mesh.isDHTEnabled()) {
|
|
485
|
+
this.addDHTLogEntry('❌ Error: WebDHT is disabled');
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
try {
|
|
490
|
+
await this.mesh.dhtUnsubscribe(key);
|
|
491
|
+
this.addDHTLogEntry(`🔕 Unsubscribed from: ${key}`);
|
|
492
|
+
} catch (error) {
|
|
493
|
+
this.addDHTLogEntry(`❌ Error unsubscribing from ${key}: ${error.message}`);
|
|
494
|
+
}
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
setupMediaControls() {
|
|
500
|
+
// Start media button
|
|
501
|
+
document.getElementById('start-media-btn').addEventListener('click', async () => {
|
|
502
|
+
await this.startMedia();
|
|
503
|
+
});
|
|
504
|
+
|
|
505
|
+
// Stop media button
|
|
506
|
+
document.getElementById('stop-media-btn').addEventListener('click', async () => {
|
|
507
|
+
await this.stopMedia();
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
// Toggle video button
|
|
511
|
+
document.getElementById('toggle-video-btn').addEventListener('click', () => {
|
|
512
|
+
this.toggleVideo();
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
// Toggle audio button
|
|
516
|
+
document.getElementById('toggle-audio-btn').addEventListener('click', () => {
|
|
517
|
+
this.toggleAudio();
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
// Audio test button
|
|
521
|
+
document.getElementById('test-audio-btn').addEventListener('click', () => {
|
|
522
|
+
this.testAudio();
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
// Media type checkboxes
|
|
526
|
+
document.getElementById('enable-video').addEventListener('change', () => {
|
|
527
|
+
this.updateMediaButtonStates();
|
|
528
|
+
});
|
|
529
|
+
|
|
530
|
+
document.getElementById('enable-audio').addEventListener('change', () => {
|
|
531
|
+
this.updateMediaButtonStates();
|
|
532
|
+
});
|
|
533
|
+
|
|
534
|
+
// Device selection dropdowns
|
|
535
|
+
document.getElementById('camera-select').addEventListener('change', () => {
|
|
536
|
+
// Auto-restart media if it's currently active
|
|
537
|
+
if (this.mesh.getMediaState().hasLocalStream) {
|
|
538
|
+
this.startMedia();
|
|
539
|
+
}
|
|
540
|
+
});
|
|
541
|
+
|
|
542
|
+
document.getElementById('microphone-select').addEventListener('change', () => {
|
|
543
|
+
// Auto-restart media if it's currently active
|
|
544
|
+
if (this.mesh.getMediaState().hasLocalStream) {
|
|
545
|
+
this.startMedia();
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
setupCollapsibleSections() {
|
|
551
|
+
const sections = [
|
|
552
|
+
'discovered-peers',
|
|
553
|
+
'connected-peers',
|
|
554
|
+
'manual-connection',
|
|
555
|
+
'settings',
|
|
556
|
+
'dht',
|
|
557
|
+
'media'
|
|
558
|
+
];
|
|
559
|
+
|
|
560
|
+
sections.forEach(sectionId => {
|
|
561
|
+
const toggle = document.getElementById(`${sectionId}-toggle`);
|
|
562
|
+
const content = document.getElementById(`${sectionId}-content`);
|
|
563
|
+
|
|
564
|
+
if (toggle && content) {
|
|
565
|
+
toggle.addEventListener('click', () => {
|
|
566
|
+
this.toggleSection(sectionId);
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
toggleSection(sectionId) {
|
|
573
|
+
const toggle = document.getElementById(`${sectionId}-toggle`);
|
|
574
|
+
const content = document.getElementById(`${sectionId}-content`);
|
|
575
|
+
|
|
576
|
+
if (!toggle || !content) {
|
|
577
|
+
console.warn(`Could not find elements for section: ${sectionId}`);
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const section = toggle.closest(`.${sectionId}`);
|
|
582
|
+
|
|
583
|
+
if (!section) {
|
|
584
|
+
console.warn(`Could not find section container for: ${sectionId}`, {
|
|
585
|
+
toggle,
|
|
586
|
+
toggleParent: toggle.parentElement,
|
|
587
|
+
toggleParentParent: toggle.parentElement?.parentElement,
|
|
588
|
+
classList: toggle.parentElement?.parentElement?.classList
|
|
589
|
+
});
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const isExpanded = toggle.getAttribute('aria-expanded') === 'true';
|
|
594
|
+
|
|
595
|
+
toggle.setAttribute('aria-expanded', !isExpanded);
|
|
596
|
+
|
|
597
|
+
// Add null check before calling setAttribute
|
|
598
|
+
if (section) {
|
|
599
|
+
section.setAttribute('aria-expanded', !isExpanded);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
if (isExpanded) {
|
|
603
|
+
content.style.display = 'none';
|
|
604
|
+
toggle.textContent = toggle.textContent.replace('▼', '▶');
|
|
605
|
+
} else {
|
|
606
|
+
content.style.display = 'block';
|
|
607
|
+
toggle.textContent = toggle.textContent.replace('▶', '▼');
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// Media-related methods
|
|
612
|
+
async initializeMedia() {
|
|
613
|
+
try {
|
|
614
|
+
// Initialize media manager
|
|
615
|
+
await this.mesh.initializeMedia();
|
|
616
|
+
|
|
617
|
+
// Populate device lists
|
|
618
|
+
await this.updateDeviceLists();
|
|
619
|
+
|
|
620
|
+
// Update button states
|
|
621
|
+
this.updateMediaButtonStates();
|
|
622
|
+
|
|
623
|
+
console.log('Media initialized successfully');
|
|
624
|
+
} catch (error) {
|
|
625
|
+
console.error('Failed to initialize media:', error);
|
|
626
|
+
this.addMessage('System', `Failed to initialize media: ${error.message}`, 'error');
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
async updateDeviceLists() {
|
|
631
|
+
try {
|
|
632
|
+
const devices = await this.mesh.enumerateMediaDevices();
|
|
633
|
+
|
|
634
|
+
// Update camera list
|
|
635
|
+
const cameraSelect = document.getElementById('camera-select');
|
|
636
|
+
if (cameraSelect) {
|
|
637
|
+
cameraSelect.innerHTML = '<option value="">Select camera...</option>';
|
|
638
|
+
devices.cameras.forEach(device => {
|
|
639
|
+
const option = document.createElement('option');
|
|
640
|
+
option.value = device.deviceId;
|
|
641
|
+
option.textContent = device.label || `Camera ${device.deviceId.substring(0, 8)}...`;
|
|
642
|
+
cameraSelect.appendChild(option);
|
|
643
|
+
});
|
|
644
|
+
cameraSelect.disabled = devices.cameras.length === 0;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// Update microphone list
|
|
648
|
+
const micSelect = document.getElementById('microphone-select');
|
|
649
|
+
if (micSelect) {
|
|
650
|
+
micSelect.innerHTML = '<option value="">Select microphone...</option>';
|
|
651
|
+
devices.microphones.forEach(device => {
|
|
652
|
+
const option = document.createElement('option');
|
|
653
|
+
option.value = device.deviceId;
|
|
654
|
+
option.textContent = device.label || `Microphone ${device.deviceId.substring(0, 8)}...`;
|
|
655
|
+
micSelect.appendChild(option);
|
|
656
|
+
});
|
|
657
|
+
micSelect.disabled = devices.microphones.length === 0;
|
|
658
|
+
}
|
|
659
|
+
} catch (error) {
|
|
660
|
+
console.error('Failed to update device lists:', error);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
updateMediaButtonStates() {
|
|
665
|
+
const videoEnabled = document.getElementById('enable-video')?.checked || false;
|
|
666
|
+
const audioEnabled = document.getElementById('enable-audio')?.checked || false;
|
|
667
|
+
const mediaState = this.mesh.getMediaState();
|
|
668
|
+
|
|
669
|
+
// Enable start button if at least one media type is selected
|
|
670
|
+
const startBtn = document.getElementById('start-media-btn');
|
|
671
|
+
if (startBtn) {
|
|
672
|
+
startBtn.disabled = !(videoEnabled || audioEnabled) || mediaState.hasLocalStream;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// Enable stop button if media is active
|
|
676
|
+
const stopBtn = document.getElementById('stop-media-btn');
|
|
677
|
+
if (stopBtn) {
|
|
678
|
+
stopBtn.disabled = !mediaState.hasLocalStream;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// Enable toggle buttons if media is active
|
|
682
|
+
const toggleVideoBtn = document.getElementById('toggle-video-btn');
|
|
683
|
+
const toggleAudioBtn = document.getElementById('toggle-audio-btn');
|
|
684
|
+
|
|
685
|
+
if (toggleVideoBtn) {
|
|
686
|
+
toggleVideoBtn.disabled = !mediaState.hasLocalStream;
|
|
687
|
+
toggleVideoBtn.textContent = mediaState.videoEnabled ? 'Turn Off Video' : 'Turn On Video';
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
if (toggleAudioBtn) {
|
|
691
|
+
toggleAudioBtn.disabled = !mediaState.hasLocalStream;
|
|
692
|
+
toggleAudioBtn.textContent = mediaState.audioEnabled ? 'Turn Off Audio' : 'Turn On Audio';
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
async startMedia() {
|
|
697
|
+
try {
|
|
698
|
+
const videoEnabled = document.getElementById('enable-video')?.checked || false;
|
|
699
|
+
const audioEnabled = document.getElementById('enable-audio')?.checked || false;
|
|
700
|
+
|
|
701
|
+
// Initialize audio context for better audio support
|
|
702
|
+
if (audioEnabled && (window.AudioContext || window.webkitAudioContext)) {
|
|
703
|
+
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
704
|
+
try {
|
|
705
|
+
const audioContext = new AudioContext();
|
|
706
|
+
if (audioContext.state === 'suspended') {
|
|
707
|
+
await audioContext.resume();
|
|
708
|
+
console.log('Audio context resumed for local media');
|
|
709
|
+
}
|
|
710
|
+
console.log('Audio context state:', audioContext.state);
|
|
711
|
+
} catch (e) {
|
|
712
|
+
console.log('Could not initialize audio context:', e);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
const deviceIds = {};
|
|
717
|
+
const cameraSelect = document.getElementById('camera-select');
|
|
718
|
+
const micSelect = document.getElementById('microphone-select');
|
|
719
|
+
|
|
720
|
+
if (cameraSelect?.value) {
|
|
721
|
+
deviceIds.camera = cameraSelect.value;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
if (micSelect?.value) {
|
|
725
|
+
deviceIds.microphone = micSelect.value;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
await this.mesh.startMedia({
|
|
729
|
+
video: videoEnabled,
|
|
730
|
+
audio: audioEnabled,
|
|
731
|
+
deviceIds
|
|
732
|
+
});
|
|
733
|
+
|
|
734
|
+
this.addMessage('System', 'Media started successfully');
|
|
735
|
+
this.updateMediaButtonStates();
|
|
736
|
+
} catch (error) {
|
|
737
|
+
console.error('Failed to start media:', error);
|
|
738
|
+
this.addMessage('System', `Failed to start media: ${error.message}`, 'error');
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
async stopMedia() {
|
|
743
|
+
try {
|
|
744
|
+
await this.mesh.stopMedia();
|
|
745
|
+
this.addMessage('System', 'Media stopped');
|
|
746
|
+
this.updateMediaButtonStates();
|
|
747
|
+
this.clearLocalVideo();
|
|
748
|
+
} catch (error) {
|
|
749
|
+
console.error('Failed to stop media:', error);
|
|
750
|
+
this.addMessage('System', `Failed to stop media: ${error.message}`, 'error');
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
toggleVideo() {
|
|
755
|
+
try {
|
|
756
|
+
const enabled = this.mesh.toggleVideo();
|
|
757
|
+
this.addMessage('System', `Video ${enabled ? 'enabled' : 'disabled'}`);
|
|
758
|
+
this.updateMediaButtonStates();
|
|
759
|
+
} catch (error) {
|
|
760
|
+
console.error('Failed to toggle video:', error);
|
|
761
|
+
this.addMessage('System', `Failed to toggle video: ${error.message}`, 'error');
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
toggleAudio() {
|
|
766
|
+
try {
|
|
767
|
+
const enabled = this.mesh.toggleAudio();
|
|
768
|
+
this.addMessage('System', `Audio ${enabled ? 'enabled' : 'disabled'}`);
|
|
769
|
+
this.updateMediaButtonStates();
|
|
770
|
+
} catch (error) {
|
|
771
|
+
console.error('Failed to toggle audio:', error);
|
|
772
|
+
this.addMessage('System', `Failed to toggle audio: ${error.message}`, 'error');
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
async testAudio() {
|
|
777
|
+
try {
|
|
778
|
+
console.log('🔊 Starting audio test...');
|
|
779
|
+
this.addMessage('System', '🔊 Testing audio system...', 'info');
|
|
780
|
+
|
|
781
|
+
// First, run diagnostics to understand current state
|
|
782
|
+
this.logPeerDiagnostics();
|
|
783
|
+
|
|
784
|
+
// Test 0: Verify we have actual peer connections (not just self)
|
|
785
|
+
const allPeers = this.mesh.getPeers();
|
|
786
|
+
const connectedPeers = allPeers.filter(peer => peer.status === 'connected');
|
|
787
|
+
const peersWithMedia = allPeers.filter(peer => {
|
|
788
|
+
const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
|
|
789
|
+
return peerConnection && (peerConnection.remoteStream || peerConnection.connection?.connectionState === 'connected');
|
|
790
|
+
});
|
|
791
|
+
|
|
792
|
+
console.log('🔊 All peers:', allPeers.length);
|
|
793
|
+
console.log('🔊 Connected peers (data channel):', connectedPeers.length);
|
|
794
|
+
console.log('🔊 Peers with media/WebRTC:', peersWithMedia.length);
|
|
795
|
+
|
|
796
|
+
// Log detailed peer status
|
|
797
|
+
allPeers.forEach(peer => {
|
|
798
|
+
const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
|
|
799
|
+
console.log(`🔊 Peer ${peer.peerId.substring(0, 8)}:`, {
|
|
800
|
+
status: peer.status,
|
|
801
|
+
webrtcState: peerConnection?.connection?.connectionState,
|
|
802
|
+
dataChannelState: peerConnection?.dataChannel?.readyState,
|
|
803
|
+
hasRemoteStream: !!peerConnection?.remoteStream,
|
|
804
|
+
hasLocalStream: !!peerConnection?.localStream
|
|
805
|
+
});
|
|
806
|
+
});
|
|
807
|
+
|
|
808
|
+
this.addMessage('System', `🔊 Found ${allPeers.length} total peers (${connectedPeers.length} with data channel, ${peersWithMedia.length} with media)`, 'info');
|
|
809
|
+
|
|
810
|
+
if (peersWithMedia.length === 0) {
|
|
811
|
+
this.addMessage('System', '❌ No peers with active media! You need to open this in TWO different browser tabs/windows and connect them.', 'error');
|
|
812
|
+
console.log('❌ NO PEERS WITH MEDIA: Open this URL in two different browser tabs and ensure they connect to each other');
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// Test each peer connection individually
|
|
817
|
+
peersWithMedia.forEach((peer, index) => {
|
|
818
|
+
const connection = this.mesh.connectionManager.peers.get(peer.peerId);
|
|
819
|
+
if (connection) {
|
|
820
|
+
console.log(`🔊 Peer ${index + 1} (${peer.peerId.substring(0, 8)}...):`);
|
|
821
|
+
|
|
822
|
+
const localStream = connection.getLocalStream();
|
|
823
|
+
const remoteStream = connection.getRemoteStream();
|
|
824
|
+
|
|
825
|
+
// Check local stream
|
|
826
|
+
if (localStream) {
|
|
827
|
+
const localAudioTracks = localStream.getAudioTracks();
|
|
828
|
+
console.log(` - Local audio tracks: ${localAudioTracks.length}`);
|
|
829
|
+
this.addMessage('System', ` Peer ${index + 1} - Local audio: ${localAudioTracks.length} tracks`, 'info');
|
|
830
|
+
localAudioTracks.forEach((track, i) => {
|
|
831
|
+
console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}...`);
|
|
832
|
+
});
|
|
833
|
+
} else {
|
|
834
|
+
console.log(' - No local stream');
|
|
835
|
+
this.addMessage('System', ` Peer ${index + 1} - No local stream`, 'warning');
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// Check remote stream
|
|
839
|
+
if (remoteStream) {
|
|
840
|
+
const remoteAudioTracks = remoteStream.getAudioTracks();
|
|
841
|
+
console.log(` - Remote audio tracks: ${remoteAudioTracks.length}`);
|
|
842
|
+
this.addMessage('System', ` Peer ${index + 1} - Remote audio: ${remoteAudioTracks.length} tracks`, remoteAudioTracks.length > 0 ? 'success' : 'warning');
|
|
843
|
+
|
|
844
|
+
remoteAudioTracks.forEach((track, i) => {
|
|
845
|
+
console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}..., readyState=${track.readyState}`);
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
// CRITICAL: Check if remote stream ID matches local stream ID (loopback detection)
|
|
849
|
+
if (localStream && remoteStream.id === localStream.id) {
|
|
850
|
+
console.error('❌ LOOPBACK DETECTED: Remote stream ID matches local stream ID!');
|
|
851
|
+
this.addMessage('System', `❌ Peer ${index + 1} - LOOPBACK: Getting own audio back!`, 'error');
|
|
852
|
+
} else {
|
|
853
|
+
console.log(`✅ Stream IDs different: local=${localStream?.id.substring(0, 8) || 'none'}, remote=${remoteStream.id.substring(0, 8)}`);
|
|
854
|
+
this.addMessage('System', `✅ Peer ${index + 1} - Stream IDs are different (good!)`, 'success');
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
// Check video elements playing this stream
|
|
858
|
+
const videoElements = document.querySelectorAll('video');
|
|
859
|
+
let foundVideoElement = false;
|
|
860
|
+
videoElements.forEach(video => {
|
|
861
|
+
if (video.srcObject === remoteStream) {
|
|
862
|
+
foundVideoElement = true;
|
|
863
|
+
console.log(` - Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}, readyState=${video.readyState}`);
|
|
864
|
+
this.addMessage('System', ` Peer ${index + 1} - Video element: volume=${video.volume}, muted=${video.muted}`, video.muted ? 'warning' : 'success');
|
|
865
|
+
}
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
if (!foundVideoElement) {
|
|
869
|
+
console.log(' - ❌ No video element found for this remote stream');
|
|
870
|
+
this.addMessage('System', ` Peer ${index + 1} - ❌ No video element displaying this stream`, 'error');
|
|
871
|
+
}
|
|
872
|
+
} else {
|
|
873
|
+
console.log(' - ❌ No remote stream');
|
|
874
|
+
this.addMessage('System', ` Peer ${index + 1} - ❌ No remote stream received`, 'error');
|
|
875
|
+
}
|
|
876
|
+
} else {
|
|
877
|
+
console.log(`❌ No connection object found for peer ${peer.peerId}`);
|
|
878
|
+
this.addMessage('System', `❌ No connection for peer ${index + 1}`, 'error');
|
|
879
|
+
}
|
|
880
|
+
});
|
|
881
|
+
|
|
882
|
+
// Test 1: Audio Context
|
|
883
|
+
if (window.AudioContext || window.webkitAudioContext) {
|
|
884
|
+
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
885
|
+
const audioContext = new AudioContext();
|
|
886
|
+
console.log('Audio context state:', audioContext.state);
|
|
887
|
+
|
|
888
|
+
if (audioContext.state === 'suspended') {
|
|
889
|
+
await audioContext.resume();
|
|
890
|
+
console.log('Audio context resumed');
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// Generate a test tone
|
|
894
|
+
const oscillator = audioContext.createOscillator();
|
|
895
|
+
const gainNode = audioContext.createGain();
|
|
896
|
+
|
|
897
|
+
oscillator.connect(gainNode);
|
|
898
|
+
gainNode.connect(audioContext.destination);
|
|
899
|
+
|
|
900
|
+
oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4 note
|
|
901
|
+
gainNode.gain.setValueAtTime(0.1, audioContext.currentTime); // Low volume
|
|
902
|
+
|
|
903
|
+
oscillator.start();
|
|
904
|
+
oscillator.stop(audioContext.currentTime + 0.5); // Play for 0.5 seconds
|
|
905
|
+
|
|
906
|
+
this.addMessage('System', '🔊 Audio test tone played (440Hz for 0.5s)', 'success');
|
|
907
|
+
} else {
|
|
908
|
+
this.addMessage('System', '❌ Audio context not supported', 'error');
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// Test 2: Check current media streams
|
|
912
|
+
const peers = this.mesh.getPeers();
|
|
913
|
+
console.log('Current peers:', peers.length);
|
|
914
|
+
|
|
915
|
+
peers.forEach(peer => {
|
|
916
|
+
const connection = this.mesh.connectionManager.peers.get(peer.peerId);
|
|
917
|
+
if (connection) {
|
|
918
|
+
const localStream = connection.getLocalStream();
|
|
919
|
+
const remoteStream = connection.getRemoteStream();
|
|
920
|
+
|
|
921
|
+
console.log(`Peer ${peer.peerId.substring(0, 8)}:`);
|
|
922
|
+
if (localStream) {
|
|
923
|
+
const audioTracks = localStream.getAudioTracks();
|
|
924
|
+
console.log(`- Local audio tracks: ${audioTracks.length}`);
|
|
925
|
+
audioTracks.forEach((track, i) => {
|
|
926
|
+
console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
if (remoteStream) {
|
|
931
|
+
const audioTracks = remoteStream.getAudioTracks();
|
|
932
|
+
console.log(`- Remote audio tracks: ${audioTracks.length}`);
|
|
933
|
+
audioTracks.forEach((track, i) => {
|
|
934
|
+
console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
|
|
935
|
+
});
|
|
936
|
+
|
|
937
|
+
// Check if there are video elements for this stream
|
|
938
|
+
const videoElements = document.querySelectorAll('video');
|
|
939
|
+
videoElements.forEach(video => {
|
|
940
|
+
if (video.srcObject === remoteStream) {
|
|
941
|
+
console.log(`- Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}`);
|
|
942
|
+
}
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
});
|
|
947
|
+
|
|
948
|
+
// Test 3: Check microphone access
|
|
949
|
+
try {
|
|
950
|
+
const testStream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
|
951
|
+
console.log('✅ Microphone access working');
|
|
952
|
+
this.addMessage('System', '✅ Microphone access: OK', 'success');
|
|
953
|
+
testStream.getTracks().forEach(track => track.stop());
|
|
954
|
+
} catch (error) {
|
|
955
|
+
console.log('❌ Microphone access failed:', error);
|
|
956
|
+
this.addMessage('System', `❌ Microphone access failed: ${error.message}`, 'error');
|
|
957
|
+
}
|
|
958
|
+
} catch (error) {
|
|
959
|
+
console.error('Audio test failed:', error);
|
|
960
|
+
this.addMessage('System', `❌ Audio test failed: ${error.message}`, 'error');
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
handleLocalStreamStarted(data) {
|
|
965
|
+
this.updateMediaButtonStates();
|
|
966
|
+
|
|
967
|
+
// Display local video if video is enabled
|
|
968
|
+
if (data.video) {
|
|
969
|
+
this.displayLocalVideo(data.stream);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
const mediaTypes = [];
|
|
973
|
+
if (data.video) mediaTypes.push('video');
|
|
974
|
+
if (data.audio) mediaTypes.push('audio');
|
|
975
|
+
|
|
976
|
+
this.addMessage('System', `Local ${mediaTypes.join(' and ')} started`);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
handleLocalStreamStopped() {
|
|
980
|
+
this.updateMediaButtonStates();
|
|
981
|
+
this.clearLocalVideo();
|
|
982
|
+
this.addMessage('System', 'Local media stopped');
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
displayLocalVideo(stream) {
|
|
986
|
+
const localVideoContainer = document.getElementById('local-video-container');
|
|
987
|
+
if (!localVideoContainer) return;
|
|
988
|
+
|
|
989
|
+
let video = localVideoContainer.querySelector('video');
|
|
990
|
+
if (!video) {
|
|
991
|
+
video = document.createElement('video');
|
|
992
|
+
video.autoplay = true;
|
|
993
|
+
video.muted = true;
|
|
994
|
+
video.playsInline = true;
|
|
995
|
+
video.style.width = '100%';
|
|
996
|
+
video.style.borderRadius = '8px';
|
|
997
|
+
localVideoContainer.appendChild(video);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
video.srcObject = stream;
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
clearLocalVideo() {
|
|
1004
|
+
const localVideoContainer = document.getElementById('local-video-container');
|
|
1005
|
+
if (localVideoContainer) {
|
|
1006
|
+
const video = localVideoContainer.querySelector('video');
|
|
1007
|
+
if (video) {
|
|
1008
|
+
video.srcObject = null;
|
|
1009
|
+
video.remove();
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
handleRemoteStream(data) {
|
|
1015
|
+
console.log('🎵 Handling remote stream:', data);
|
|
1016
|
+
const { peerId, stream } = data;
|
|
1017
|
+
|
|
1018
|
+
// CRITICAL: Prevent audio loopback - check if this is our own stream
|
|
1019
|
+
if (peerId === this.mesh.peerId) {
|
|
1020
|
+
console.warn('🚨 LOOPBACK DETECTED: Received our own stream as remote! This should not happen.');
|
|
1021
|
+
console.warn('Stream ID:', stream.id);
|
|
1022
|
+
// Still display it but it will be muted by displayRemoteVideo
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// Detailed audio analysis
|
|
1026
|
+
const audioTracks = stream.getAudioTracks();
|
|
1027
|
+
const videoTracks = stream.getVideoTracks();
|
|
1028
|
+
|
|
1029
|
+
console.log(`Stream from ${peerId.substring(0, 8)}: ${audioTracks.length} audio, ${videoTracks.length} video tracks`);
|
|
1030
|
+
|
|
1031
|
+
audioTracks.forEach((track, i) => {
|
|
1032
|
+
console.log(`🎵 Audio track ${i}:`, {
|
|
1033
|
+
id: track.id,
|
|
1034
|
+
kind: track.kind,
|
|
1035
|
+
enabled: track.enabled,
|
|
1036
|
+
readyState: track.readyState,
|
|
1037
|
+
muted: track.muted,
|
|
1038
|
+
label: track.label
|
|
1039
|
+
});
|
|
1040
|
+
|
|
1041
|
+
// Add track event listeners for state monitoring
|
|
1042
|
+
track.addEventListener('ended', () => {
|
|
1043
|
+
console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} ENDED`);
|
|
1044
|
+
});
|
|
1045
|
+
|
|
1046
|
+
track.addEventListener('mute', () => {
|
|
1047
|
+
console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} MUTED`);
|
|
1048
|
+
});
|
|
1049
|
+
|
|
1050
|
+
track.addEventListener('unmute', () => {
|
|
1051
|
+
console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} UNMUTED`);
|
|
1052
|
+
});
|
|
1053
|
+
});
|
|
1054
|
+
|
|
1055
|
+
this.displayRemoteVideo(peerId, stream);
|
|
1056
|
+
|
|
1057
|
+
// Audio data summary
|
|
1058
|
+
const audioSummary = {
|
|
1059
|
+
peerIdShort: peerId.substring(0, 8),
|
|
1060
|
+
audioTrackCount: audioTracks.length,
|
|
1061
|
+
videoTrackCount: videoTracks.length,
|
|
1062
|
+
audioTracksEnabled: audioTracks.filter(t => t.enabled).length,
|
|
1063
|
+
streamActive: stream.active,
|
|
1064
|
+
streamId: stream.id
|
|
1065
|
+
};
|
|
1066
|
+
|
|
1067
|
+
console.log(`🎵 AUDIO DATA EXPECTATION for peer ${audioSummary.peerIdShort}:`, audioSummary);
|
|
1068
|
+
|
|
1069
|
+
if (audioTracks.length > 0) {
|
|
1070
|
+
console.log(`✅ EXPECTING AUDIO DATA from peer ${audioSummary.peerIdShort} - ${audioSummary.audioTracksEnabled}/${audioSummary.audioTrackCount} tracks enabled`);
|
|
1071
|
+
} else {
|
|
1072
|
+
console.log(`❌ NO AUDIO TRACKS from peer ${audioSummary.peerIdShort} - video only`);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
this.addMessage('System', `🎵 Remote stream received from ${peerId.substring(0, 8)}... (${audioTracks.length} audio, ${videoTracks.length} video)`);
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
displayRemoteVideo(peerId, stream) {
|
|
1079
|
+
console.log(`Displaying remote video for ${peerId}:`, stream);
|
|
1080
|
+
console.log('Stream tracks:', stream.getTracks().map(t => ({ kind: t.kind, enabled: t.enabled })));
|
|
1081
|
+
|
|
1082
|
+
// CRITICAL: Prevent audio loopback - check if this is our own stream
|
|
1083
|
+
const isOwnStream = peerId === this.mesh.peerId;
|
|
1084
|
+
if (isOwnStream) {
|
|
1085
|
+
console.warn('🚨 LOOPBACK DETECTED: Received our own stream! Muting audio to prevent feedback.');
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
const remoteVideosContainer = document.getElementById('remote-videos-container');
|
|
1089
|
+
if (!remoteVideosContainer) return;
|
|
1090
|
+
|
|
1091
|
+
let remoteVideoItem = remoteVideosContainer.querySelector(`[data-peer-id="${peerId}"]`);
|
|
1092
|
+
|
|
1093
|
+
if (!remoteVideoItem) {
|
|
1094
|
+
remoteVideoItem = document.createElement('div');
|
|
1095
|
+
remoteVideoItem.className = 'remote-video-item';
|
|
1096
|
+
remoteVideoItem.setAttribute('data-peer-id', peerId);
|
|
1097
|
+
|
|
1098
|
+
const title = document.createElement('div');
|
|
1099
|
+
title.className = 'video-title';
|
|
1100
|
+
title.textContent = `Peer ${peerId.substring(0, 8)}...`;
|
|
1101
|
+
|
|
1102
|
+
const video = document.createElement('video');
|
|
1103
|
+
video.autoplay = true;
|
|
1104
|
+
video.playsInline = true;
|
|
1105
|
+
video.controls = true;
|
|
1106
|
+
// CRITICAL: Mute if this is our own stream to prevent audio feedback
|
|
1107
|
+
video.muted = isOwnStream; // Mute our own audio, unmute others
|
|
1108
|
+
video.style.width = '100%';
|
|
1109
|
+
video.style.borderRadius = '8px';
|
|
1110
|
+
|
|
1111
|
+
// Enhanced audio debugging
|
|
1112
|
+
video.addEventListener('loadedmetadata', () => {
|
|
1113
|
+
console.log('Video element loaded metadata:', {
|
|
1114
|
+
duration: video.duration,
|
|
1115
|
+
audioTracks: video.audioTracks?.length || 'N/A',
|
|
1116
|
+
volume: video.volume,
|
|
1117
|
+
muted: video.muted
|
|
1118
|
+
});
|
|
1119
|
+
|
|
1120
|
+
video.play().then(() => {
|
|
1121
|
+
console.log('Video/audio playback started successfully');
|
|
1122
|
+
// Check audio context state
|
|
1123
|
+
if (window.AudioContext || window.webkitAudioContext) {
|
|
1124
|
+
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
1125
|
+
const audioContext = new AudioContext();
|
|
1126
|
+
console.log('Audio context state:', audioContext.state);
|
|
1127
|
+
if (audioContext.state === 'suspended') {
|
|
1128
|
+
console.log('Audio context is suspended - may need user interaction');
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
// Hide any play button if playback started
|
|
1132
|
+
const playButton = remoteVideoItem.querySelector('.manual-play-button');
|
|
1133
|
+
if (playButton) {
|
|
1134
|
+
playButton.style.display = 'none';
|
|
1135
|
+
}
|
|
1136
|
+
}).catch(error => {
|
|
1137
|
+
console.log('Autoplay failed, user interaction required:', error);
|
|
1138
|
+
// Show a manual play button
|
|
1139
|
+
const playButton = document.createElement('button');
|
|
1140
|
+
playButton.className = 'manual-play-button';
|
|
1141
|
+
playButton.textContent = '▶ Click to Play Audio';
|
|
1142
|
+
playButton.style.cssText = 'position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 10; padding: 10px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;';
|
|
1143
|
+
|
|
1144
|
+
playButton.addEventListener('click', async () => {
|
|
1145
|
+
try {
|
|
1146
|
+
await video.play();
|
|
1147
|
+
playButton.style.display = 'none';
|
|
1148
|
+
console.log('Manual play successful');
|
|
1149
|
+
} catch (e) {
|
|
1150
|
+
console.error('Manual play failed:', e);
|
|
1151
|
+
}
|
|
1152
|
+
});
|
|
1153
|
+
|
|
1154
|
+
remoteVideoItem.style.position = 'relative';
|
|
1155
|
+
remoteVideoItem.appendChild(playButton);
|
|
1156
|
+
});
|
|
1157
|
+
});
|
|
1158
|
+
|
|
1159
|
+
// Add event listeners for audio debugging
|
|
1160
|
+
video.addEventListener('play', () => {
|
|
1161
|
+
console.log('Video element started playing');
|
|
1162
|
+
});
|
|
1163
|
+
|
|
1164
|
+
video.addEventListener('pause', () => {
|
|
1165
|
+
console.log('Video element paused');
|
|
1166
|
+
});
|
|
1167
|
+
|
|
1168
|
+
video.addEventListener('volumechange', () => {
|
|
1169
|
+
console.log('Volume changed:', video.volume, 'Muted:', video.muted);
|
|
1170
|
+
});
|
|
1171
|
+
|
|
1172
|
+
const status = document.createElement('div');
|
|
1173
|
+
status.className = 'video-status';
|
|
1174
|
+
|
|
1175
|
+
remoteVideoItem.appendChild(title);
|
|
1176
|
+
remoteVideoItem.appendChild(video);
|
|
1177
|
+
remoteVideoItem.appendChild(status);
|
|
1178
|
+
|
|
1179
|
+
remoteVideosContainer.appendChild(remoteVideoItem);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
const video = remoteVideoItem.querySelector('video');
|
|
1183
|
+
const status = remoteVideoItem.querySelector('.video-status');
|
|
1184
|
+
|
|
1185
|
+
video.srcObject = stream;
|
|
1186
|
+
|
|
1187
|
+
// EXPLICIT AUDIO DEBUGGING
|
|
1188
|
+
console.log('🎵 Setting srcObject for video element:', {
|
|
1189
|
+
stream,
|
|
1190
|
+
streamId: stream.id,
|
|
1191
|
+
streamActive: stream.active,
|
|
1192
|
+
videoElement: video,
|
|
1193
|
+
videoMuted: video.muted,
|
|
1194
|
+
videoVolume: video.volume,
|
|
1195
|
+
isOwnStream
|
|
1196
|
+
});
|
|
1197
|
+
|
|
1198
|
+
const audioTracks = stream.getAudioTracks();
|
|
1199
|
+
const videoTracks = stream.getVideoTracks();
|
|
1200
|
+
|
|
1201
|
+
console.log('🎵 Stream tracks assigned:', {
|
|
1202
|
+
audioTracks: audioTracks.map(t => ({
|
|
1203
|
+
id: t.id,
|
|
1204
|
+
enabled: t.enabled,
|
|
1205
|
+
readyState: t.readyState,
|
|
1206
|
+
muted: t.muted
|
|
1207
|
+
})),
|
|
1208
|
+
videoTracks: videoTracks.map(t => ({
|
|
1209
|
+
id: t.id,
|
|
1210
|
+
enabled: t.enabled,
|
|
1211
|
+
readyState: t.readyState,
|
|
1212
|
+
muted: t.muted
|
|
1213
|
+
}))
|
|
1214
|
+
});
|
|
1215
|
+
|
|
1216
|
+
// CRITICAL: Set audio state based on whether this is our own stream
|
|
1217
|
+
if (isOwnStream) {
|
|
1218
|
+
console.warn('🚨 Muting our own stream to prevent audio feedback');
|
|
1219
|
+
video.muted = true;
|
|
1220
|
+
video.volume = 0;
|
|
1221
|
+
} else {
|
|
1222
|
+
// Only unmute if this is NOT our own stream
|
|
1223
|
+
video.muted = false;
|
|
1224
|
+
video.volume = 1.0;
|
|
1225
|
+
|
|
1226
|
+
// Setup audio playback monitoring for remote streams
|
|
1227
|
+
this.setupAudioPlaybackMonitoring(video, peerId, audioTracks);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// Update status based on stream tracks
|
|
1231
|
+
console.log(`Video tracks: ${videoTracks.length}, Audio tracks: ${audioTracks.length}`);
|
|
1232
|
+
audioTracks.forEach((track, i) => {
|
|
1233
|
+
console.log(`Audio track ${i}:`, { enabled: track.enabled, muted: track.muted, label: track.label });
|
|
1234
|
+
});
|
|
1235
|
+
|
|
1236
|
+
// For audio-only streams, ensure the video element is properly configured
|
|
1237
|
+
if (audioTracks.length > 0 && videoTracks.length === 0) {
|
|
1238
|
+
console.log('Audio-only stream detected - configuring for audio playback');
|
|
1239
|
+
video.style.height = '60px'; // Smaller height for audio-only
|
|
1240
|
+
video.style.backgroundColor = '#f0f0f0';
|
|
1241
|
+
|
|
1242
|
+
// Force audio to play by trying to resume audio context
|
|
1243
|
+
if (window.AudioContext || window.webkitAudioContext) {
|
|
1244
|
+
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
1245
|
+
try {
|
|
1246
|
+
const audioContext = new AudioContext();
|
|
1247
|
+
if (audioContext.state === 'suspended') {
|
|
1248
|
+
audioContext.resume().then(() => {
|
|
1249
|
+
console.log('Audio context resumed for remote stream');
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
// Test audio by creating a brief analysis
|
|
1254
|
+
try {
|
|
1255
|
+
const source = audioContext.createMediaStreamSource(stream);
|
|
1256
|
+
const analyser = audioContext.createAnalyser();
|
|
1257
|
+
source.connect(analyser);
|
|
1258
|
+
|
|
1259
|
+
const dataArray = new Uint8Array(analyser.frequencyBinCount);
|
|
1260
|
+
const checkAudio = () => {
|
|
1261
|
+
analyser.getByteFrequencyData(dataArray);
|
|
1262
|
+
const sum = dataArray.reduce((a, b) => a + b, 0);
|
|
1263
|
+
if (sum > 0) {
|
|
1264
|
+
console.log('Remote audio data detected! Sum:', sum);
|
|
1265
|
+
}
|
|
1266
|
+
};
|
|
1267
|
+
|
|
1268
|
+
// Check audio data periodically
|
|
1269
|
+
const audioChecker = setInterval(checkAudio, 1000);
|
|
1270
|
+
setTimeout(() => clearInterval(audioChecker), 10000); // Stop after 10 seconds
|
|
1271
|
+
} catch (audioAnalysisError) {
|
|
1272
|
+
console.log('Could not analyze remote audio:', audioAnalysisError);
|
|
1273
|
+
}
|
|
1274
|
+
} catch (e) {
|
|
1275
|
+
console.log('Could not create/resume audio context:', e);
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
const statusText = [];
|
|
1281
|
+
if (videoTracks.length > 0) statusText.push('Video');
|
|
1282
|
+
if (audioTracks.length > 0) statusText.push('Audio');
|
|
1283
|
+
|
|
1284
|
+
status.textContent = statusText.length > 0 ? statusText.join(' + ') : 'Audio only';
|
|
1285
|
+
status.style.color = '#28a745';
|
|
1286
|
+
|
|
1287
|
+
this.addMessage('System', `Receiving ${statusText.join(' + ')} from ${peerId.substring(0, 8)}...`);
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
/**
|
|
1291
|
+
* Setup audio playback monitoring for video elements playing remote streams
|
|
1292
|
+
*/
|
|
1293
|
+
setupAudioPlaybackMonitoring(videoElement, peerId, audioTracks) {
|
|
1294
|
+
const peerIdShort = peerId.substring(0, 8);
|
|
1295
|
+
console.log(`🎵 Setting up audio playback monitoring for peer ${peerIdShort}`);
|
|
1296
|
+
|
|
1297
|
+
if (audioTracks.length === 0) {
|
|
1298
|
+
console.log(`🎵 No audio tracks to monitor for peer ${peerIdShort}`);
|
|
1299
|
+
return;
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
try {
|
|
1303
|
+
// Monitor video element audio events
|
|
1304
|
+
videoElement.addEventListener('play', () => {
|
|
1305
|
+
console.log(`🎵 Video element started playing for peer ${peerIdShort}`, {
|
|
1306
|
+
muted: videoElement.muted,
|
|
1307
|
+
volume: videoElement.volume,
|
|
1308
|
+
audioTracks: audioTracks.length
|
|
1309
|
+
});
|
|
1310
|
+
});
|
|
1311
|
+
|
|
1312
|
+
videoElement.addEventListener('pause', () => {
|
|
1313
|
+
console.log(`🎵 Video element paused for peer ${peerIdShort}`);
|
|
1314
|
+
});
|
|
1315
|
+
|
|
1316
|
+
videoElement.addEventListener('volumechange', () => {
|
|
1317
|
+
console.log(`🎵 Volume changed for peer ${peerIdShort}:`, {
|
|
1318
|
+
volume: videoElement.volume,
|
|
1319
|
+
muted: videoElement.muted
|
|
1320
|
+
});
|
|
1321
|
+
});
|
|
1322
|
+
|
|
1323
|
+
// Create audio context for monitoring actual audio data playback
|
|
1324
|
+
const AudioContext = window.AudioContext || window.webkitAudioContext;
|
|
1325
|
+
if (!AudioContext) {
|
|
1326
|
+
console.warn('🎵 AudioContext not available - basic monitoring only');
|
|
1327
|
+
return;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
// Wait for video to load before setting up audio analysis
|
|
1331
|
+
const setupAudioAnalysis = () => {
|
|
1332
|
+
try {
|
|
1333
|
+
const audioContext = new AudioContext();
|
|
1334
|
+
const source = audioContext.createMediaElementSource(videoElement);
|
|
1335
|
+
const analyser = audioContext.createAnalyser();
|
|
1336
|
+
const gainNode = audioContext.createGain();
|
|
1337
|
+
|
|
1338
|
+
analyser.fftSize = 256;
|
|
1339
|
+
const bufferLength = analyser.frequencyBinCount;
|
|
1340
|
+
const dataArray = new Uint8Array(bufferLength);
|
|
1341
|
+
|
|
1342
|
+
// Connect: source -> analyser -> gain -> destination
|
|
1343
|
+
source.connect(analyser);
|
|
1344
|
+
analyser.connect(gainNode);
|
|
1345
|
+
gainNode.connect(audioContext.destination);
|
|
1346
|
+
|
|
1347
|
+
let lastLogTime = 0;
|
|
1348
|
+
let totalSamples = 0;
|
|
1349
|
+
let playbackSamples = 0;
|
|
1350
|
+
let maxPlaybackLevel = 0;
|
|
1351
|
+
|
|
1352
|
+
const monitorPlayback = () => {
|
|
1353
|
+
if (videoElement.paused || videoElement.ended) {
|
|
1354
|
+
return; // Stop monitoring if playback stopped
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
analyser.getByteFrequencyData(dataArray);
|
|
1358
|
+
|
|
1359
|
+
// Calculate playback audio level
|
|
1360
|
+
const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
|
|
1361
|
+
const currentTime = Date.now();
|
|
1362
|
+
|
|
1363
|
+
totalSamples++;
|
|
1364
|
+
if (average > 3) { // Lower threshold for playback detection
|
|
1365
|
+
playbackSamples++;
|
|
1366
|
+
maxPlaybackLevel = Math.max(maxPlaybackLevel, average);
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
// Log every 3 seconds
|
|
1370
|
+
if (currentTime - lastLogTime > 3000) {
|
|
1371
|
+
const playbackActivity = totalSamples > 0 ? (playbackSamples / totalSamples * 100) : 0;
|
|
1372
|
+
console.log(`🔊 Audio PLAYBACK from peer ${peerIdShort}:`, {
|
|
1373
|
+
videoElementMuted: videoElement.muted,
|
|
1374
|
+
videoElementVolume: videoElement.volume,
|
|
1375
|
+
currentPlaybackLevel: Math.round(average),
|
|
1376
|
+
maxPlaybackLevel: Math.round(maxPlaybackLevel),
|
|
1377
|
+
playbackActivityPercent: Math.round(playbackActivity),
|
|
1378
|
+
samplesAnalyzed: totalSamples,
|
|
1379
|
+
audioBeingPlayed: playbackSamples > 0,
|
|
1380
|
+
audioContextState: audioContext.state
|
|
1381
|
+
});
|
|
1382
|
+
|
|
1383
|
+
lastLogTime = currentTime;
|
|
1384
|
+
totalSamples = 0;
|
|
1385
|
+
playbackSamples = 0;
|
|
1386
|
+
maxPlaybackLevel = 0;
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
// Continue monitoring
|
|
1390
|
+
if (!videoElement.paused && !videoElement.ended) {
|
|
1391
|
+
requestAnimationFrame(monitorPlayback);
|
|
1392
|
+
}
|
|
1393
|
+
};
|
|
1394
|
+
|
|
1395
|
+
// Start monitoring when video plays
|
|
1396
|
+
videoElement.addEventListener('play', () => {
|
|
1397
|
+
console.log(`🔊 Starting audio playback monitoring for peer ${peerIdShort}`);
|
|
1398
|
+
if (audioContext.state === 'suspended') {
|
|
1399
|
+
audioContext.resume().then(() => {
|
|
1400
|
+
requestAnimationFrame(monitorPlayback);
|
|
1401
|
+
});
|
|
1402
|
+
} else {
|
|
1403
|
+
requestAnimationFrame(monitorPlayback);
|
|
1404
|
+
}
|
|
1405
|
+
});
|
|
1406
|
+
|
|
1407
|
+
console.log(`🔊 Audio playback analysis setup complete for peer ${peerIdShort}`);
|
|
1408
|
+
} catch (error) {
|
|
1409
|
+
console.error(`🔊 Failed to setup audio playback analysis for peer ${peerIdShort}:`, error);
|
|
1410
|
+
}
|
|
1411
|
+
};
|
|
1412
|
+
|
|
1413
|
+
if (videoElement.readyState >= 1) {
|
|
1414
|
+
// Video metadata already loaded
|
|
1415
|
+
setupAudioAnalysis();
|
|
1416
|
+
} else {
|
|
1417
|
+
// Wait for metadata to load
|
|
1418
|
+
videoElement.addEventListener('loadedmetadata', setupAudioAnalysis, { once: true });
|
|
1419
|
+
}
|
|
1420
|
+
} catch (error) {
|
|
1421
|
+
console.error(`🎵 Failed to setup audio playback monitoring for peer ${peerIdShort}:`, error);
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
/**
|
|
1426
|
+
* Diagnostic method to log complete peer connection state
|
|
1427
|
+
*/
|
|
1428
|
+
logPeerDiagnostics() {
|
|
1429
|
+
console.log('🔍 PEER DIAGNOSTICS:');
|
|
1430
|
+
const allPeers = this.mesh.getPeers();
|
|
1431
|
+
|
|
1432
|
+
console.log(`📊 Total peers in mesh: ${allPeers.length}`);
|
|
1433
|
+
|
|
1434
|
+
allPeers.forEach((peer, index) => {
|
|
1435
|
+
const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
|
|
1436
|
+
|
|
1437
|
+
console.log(`\n🔍 Peer ${index + 1}: ${peer.peerId.substring(0, 8)}...`);
|
|
1438
|
+
console.log(` Status: ${peer.status}`);
|
|
1439
|
+
|
|
1440
|
+
if (peerConnection) {
|
|
1441
|
+
console.log(` WebRTC Connection State: ${peerConnection.connection?.connectionState || 'none'}`);
|
|
1442
|
+
console.log(` ICE Connection State: ${peerConnection.connection?.iceConnectionState || 'none'}`);
|
|
1443
|
+
console.log(` Data Channel State: ${peerConnection.dataChannel?.readyState || 'none'}`);
|
|
1444
|
+
console.log(` Data Channel Ready: ${peerConnection.dataChannelReady}`);
|
|
1445
|
+
console.log(` Has Local Stream: ${!!peerConnection.localStream}`);
|
|
1446
|
+
console.log(` Has Remote Stream: ${!!peerConnection.remoteStream}`);
|
|
1447
|
+
|
|
1448
|
+
if (peerConnection.localStream) {
|
|
1449
|
+
const audioTracks = peerConnection.localStream.getAudioTracks();
|
|
1450
|
+
const videoTracks = peerConnection.localStream.getVideoTracks();
|
|
1451
|
+
console.log(` Local Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
if (peerConnection.remoteStream) {
|
|
1455
|
+
const audioTracks = peerConnection.remoteStream.getAudioTracks();
|
|
1456
|
+
const videoTracks = peerConnection.remoteStream.getVideoTracks();
|
|
1457
|
+
console.log(` Remote Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
|
|
1458
|
+
}
|
|
1459
|
+
} else {
|
|
1460
|
+
console.log(' ❌ No PeerConnection object found');
|
|
1461
|
+
}
|
|
1462
|
+
});
|
|
1463
|
+
|
|
1464
|
+
console.log('\n🔍 END PEER DIAGNOSTICS\n');
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// Existing UI methods (keeping the rest of the original functionality)
|
|
1468
|
+
async handleConnect() {
|
|
1469
|
+
const url = document.getElementById('signaling-url').value.trim();
|
|
1470
|
+
if (!url) {
|
|
1471
|
+
this.addMessage('System', 'Please enter a signaling server URL', 'error');
|
|
1472
|
+
return;
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
try {
|
|
1476
|
+
this.updateButtonStates({ connecting: true });
|
|
1477
|
+
await this.mesh.connect(url);
|
|
1478
|
+
} catch (error) {
|
|
1479
|
+
console.error('Connection failed:', error);
|
|
1480
|
+
this.addMessage('System', `Connection failed: ${error.message}`, 'error');
|
|
1481
|
+
this.updateButtonStates({ connecting: false });
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
async handleDisconnect() {
|
|
1486
|
+
try {
|
|
1487
|
+
this.updateButtonStates({ disconnecting: true });
|
|
1488
|
+
await this.mesh.disconnect();
|
|
1489
|
+
} catch (error) {
|
|
1490
|
+
console.error('Disconnection failed:', error);
|
|
1491
|
+
this.addMessage('System', `Disconnection failed: ${error.message}`, 'error');
|
|
1492
|
+
} finally {
|
|
1493
|
+
this.updateButtonStates({ disconnecting: false });
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
async handleCleanup() {
|
|
1498
|
+
const now = Date.now();
|
|
1499
|
+
const timeSinceLastCleanup = now - this.lastCleanupTime;
|
|
1500
|
+
|
|
1501
|
+
if (timeSinceLastCleanup < 5000) {
|
|
1502
|
+
const remaining = Math.ceil((5000 - timeSinceLastCleanup) / 1000);
|
|
1503
|
+
this.addMessage('System', `Cleanup on cooldown (${remaining}s remaining)`, 'warning');
|
|
1504
|
+
return;
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
try {
|
|
1508
|
+
this.lastCleanupTime = now;
|
|
1509
|
+
await this.mesh.cleanupSignalingData();
|
|
1510
|
+
this.addMessage('System', 'Signaling data cleanup initiated');
|
|
1511
|
+
} catch (error) {
|
|
1512
|
+
console.error('Cleanup failed:', error);
|
|
1513
|
+
this.addMessage('System', `Cleanup failed: ${error.message}`, 'error');
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
async handleHealthCheck() {
|
|
1518
|
+
try {
|
|
1519
|
+
const result = await this.mesh.performHealthCheck();
|
|
1520
|
+
if (result.healthy) {
|
|
1521
|
+
this.addMessage('System', 'Health check passed - all systems nominal', 'info');
|
|
1522
|
+
} else {
|
|
1523
|
+
this.addMessage('System', `Health check failed: ${result.issues.join(', ')}`, 'warning');
|
|
1524
|
+
}
|
|
1525
|
+
} catch (error) {
|
|
1526
|
+
console.error('Health check failed:', error);
|
|
1527
|
+
this.addMessage('System', `Health check error: ${error.message}`, 'error');
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
sendMessage() {
|
|
1532
|
+
const messageInput = document.getElementById('message-input');
|
|
1533
|
+
const dmTargetInput = document.getElementById('dm-target-input');
|
|
1534
|
+
const message = messageInput.value.trim();
|
|
1535
|
+
const dmTarget = dmTargetInput.value.trim();
|
|
1536
|
+
|
|
1537
|
+
if (!message) return;
|
|
1538
|
+
|
|
1539
|
+
try {
|
|
1540
|
+
if (dmTarget) {
|
|
1541
|
+
// Validate peer ID format
|
|
1542
|
+
if (!window.PeerPigeonMesh.validatePeerId(dmTarget)) {
|
|
1543
|
+
this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
// Send direct message
|
|
1548
|
+
const success = this.mesh.sendDirectMessage(dmTarget, message);
|
|
1549
|
+
if (success) {
|
|
1550
|
+
this.addMessage('You', `(DM to ${dmTarget.substring(0, 8)}...) ${message}`, 'own');
|
|
1551
|
+
} else {
|
|
1552
|
+
this.addMessage('System', `Failed to send direct message to ${dmTarget.substring(0, 8)}...`, 'error');
|
|
1553
|
+
}
|
|
1554
|
+
} else {
|
|
1555
|
+
// Send broadcast message
|
|
1556
|
+
// this.mesh.broadcastMessage(message);
|
|
1557
|
+
this.mesh.sendMessage(message);
|
|
1558
|
+
this.addMessage('You', message, 'own');
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
messageInput.value = '';
|
|
1562
|
+
} catch (error) {
|
|
1563
|
+
console.error('Failed to send message:', error);
|
|
1564
|
+
this.addMessage('System', `Failed to send message: ${error.message}`, 'error');
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
connectToPeer() {
|
|
1569
|
+
const targetPeerInput = document.getElementById('target-peer');
|
|
1570
|
+
const targetPeerId = targetPeerInput.value.trim();
|
|
1571
|
+
|
|
1572
|
+
if (!targetPeerId) {
|
|
1573
|
+
this.addMessage('System', 'Please enter a peer ID', 'error');
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
if (!window.PeerPigeonMesh.validatePeerId(targetPeerId)) {
|
|
1578
|
+
this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
if (targetPeerId === this.mesh.peerId) {
|
|
1583
|
+
this.addMessage('System', 'Cannot connect to yourself', 'error');
|
|
1584
|
+
return;
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
try {
|
|
1588
|
+
this.mesh.connectToPeer(targetPeerId);
|
|
1589
|
+
this.addMessage('System', `Attempting to connect to ${targetPeerId.substring(0, 8)}...`);
|
|
1590
|
+
targetPeerInput.value = '';
|
|
1591
|
+
} catch (error) {
|
|
1592
|
+
console.error('Failed to initiate connection:', error);
|
|
1593
|
+
this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
/**
|
|
1598
|
+
* Connect to peer from button click (for onclick handlers)
|
|
1599
|
+
*/
|
|
1600
|
+
connectToPeerFromButton(button) {
|
|
1601
|
+
const peerId = button.getAttribute('data-peer-id');
|
|
1602
|
+
if (!peerId) {
|
|
1603
|
+
this.addMessage('System', 'Invalid peer ID in button', 'error');
|
|
1604
|
+
return;
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
// Disable button to prevent double-clicks
|
|
1608
|
+
button.disabled = true;
|
|
1609
|
+
button.textContent = 'Connecting...';
|
|
1610
|
+
|
|
1611
|
+
try {
|
|
1612
|
+
this.mesh.connectToPeer(peerId);
|
|
1613
|
+
this.addMessage('System', `Attempting to connect to ${peerId.substring(0, 8)}...`);
|
|
1614
|
+
|
|
1615
|
+
// Re-enable button after a delay
|
|
1616
|
+
setTimeout(() => {
|
|
1617
|
+
button.disabled = false;
|
|
1618
|
+
button.textContent = 'Connect';
|
|
1619
|
+
}, 3000);
|
|
1620
|
+
} catch (error) {
|
|
1621
|
+
console.error('Failed to initiate connection:', error);
|
|
1622
|
+
this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
|
|
1623
|
+
|
|
1624
|
+
// Re-enable button immediately on error
|
|
1625
|
+
button.disabled = false;
|
|
1626
|
+
button.textContent = 'Connect';
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
updateUI() {
|
|
1631
|
+
// Update peer ID display
|
|
1632
|
+
const peerIdElement = document.getElementById('peer-id');
|
|
1633
|
+
if (peerIdElement && this.mesh.peerId) {
|
|
1634
|
+
peerIdElement.textContent = this.mesh.peerId;
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
// Update status
|
|
1638
|
+
this.updateStatus();
|
|
1639
|
+
|
|
1640
|
+
// Update button states
|
|
1641
|
+
this.updateButtonStates();
|
|
1642
|
+
|
|
1643
|
+
// Update peer lists
|
|
1644
|
+
this.updateConnectedPeers();
|
|
1645
|
+
this.updateDiscoveredPeers();
|
|
1646
|
+
|
|
1647
|
+
// Update settings from mesh state
|
|
1648
|
+
this.updateSettings();
|
|
1649
|
+
|
|
1650
|
+
// Update DHT status
|
|
1651
|
+
this.updateDHTStatus();
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
updateStatus() {
|
|
1655
|
+
const statusElement = document.getElementById('status');
|
|
1656
|
+
if (!statusElement) return;
|
|
1657
|
+
|
|
1658
|
+
const status = this.mesh.getStatus();
|
|
1659
|
+
const connectionStatus = status.connected ? 'connected' : 'disconnected';
|
|
1660
|
+
statusElement.textContent = connectionStatus.charAt(0).toUpperCase() + connectionStatus.slice(1);
|
|
1661
|
+
statusElement.className = `status ${connectionStatus.toLowerCase()}`;
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
updateButtonStates(options = {}) {
|
|
1665
|
+
const connectBtn = document.getElementById('connect-btn');
|
|
1666
|
+
const disconnectBtn = document.getElementById('disconnect-btn');
|
|
1667
|
+
const cleanupBtn = document.getElementById('cleanup-btn');
|
|
1668
|
+
const healthCheckBtn = document.getElementById('health-check-btn');
|
|
1669
|
+
|
|
1670
|
+
const isConnected = this.mesh.connected;
|
|
1671
|
+
const isConnecting = options.connecting || false;
|
|
1672
|
+
const isDisconnecting = options.disconnecting || false;
|
|
1673
|
+
|
|
1674
|
+
if (connectBtn) {
|
|
1675
|
+
connectBtn.disabled = isConnected || isConnecting;
|
|
1676
|
+
connectBtn.textContent = isConnecting ? 'Connecting...' : 'Connect';
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
if (disconnectBtn) {
|
|
1680
|
+
disconnectBtn.disabled = !isConnected || isDisconnecting;
|
|
1681
|
+
disconnectBtn.textContent = isDisconnecting ? 'Disconnecting...' : 'Disconnect';
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
if (cleanupBtn) {
|
|
1685
|
+
cleanupBtn.disabled = !isConnected;
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
if (healthCheckBtn) {
|
|
1689
|
+
healthCheckBtn.disabled = !isConnected;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
updateConnectedPeers() {
|
|
1694
|
+
const peersList = document.getElementById('peers-list');
|
|
1695
|
+
const connectedPeersCount = document.getElementById('connected-peers-count');
|
|
1696
|
+
|
|
1697
|
+
if (!peersList || !connectedPeersCount) return;
|
|
1698
|
+
|
|
1699
|
+
const peers = this.mesh.getPeers();
|
|
1700
|
+
connectedPeersCount.textContent = peers.length;
|
|
1701
|
+
|
|
1702
|
+
if (peers.length === 0) {
|
|
1703
|
+
peersList.innerHTML = '<p class="empty-state">No peers connected</p>';
|
|
1704
|
+
return;
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
peersList.innerHTML = peers.map(peer => {
|
|
1708
|
+
// peer is a plain object: { peerId, status, isInitiator, connectionStartTime }
|
|
1709
|
+
const statusClass = peer.status === 'connected' ? 'connected' : 'connecting';
|
|
1710
|
+
const connectionTime = ((Date.now() - peer.connectionStartTime) / 1000).toFixed(1);
|
|
1711
|
+
|
|
1712
|
+
return `
|
|
1713
|
+
<div class="peer-item">
|
|
1714
|
+
<div class="peer-info">
|
|
1715
|
+
<span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
|
|
1716
|
+
<span class="peer-status ${statusClass}">${peer.status}</span>
|
|
1717
|
+
</div>
|
|
1718
|
+
<div class="peer-details">
|
|
1719
|
+
<small>Connected: ${connectionTime}s ago</small>
|
|
1720
|
+
<small>Role: ${peer.isInitiator ? 'Initiator' : 'Receiver'}</small>
|
|
1721
|
+
</div>
|
|
1722
|
+
</div>
|
|
1723
|
+
`;
|
|
1724
|
+
}).join('');
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
updateDiscoveredPeers() {
|
|
1728
|
+
const discoveredPeersList = document.getElementById('discovered-peers-list');
|
|
1729
|
+
const discoveredPeersCount = document.getElementById('discovered-peers-count');
|
|
1730
|
+
|
|
1731
|
+
if (!discoveredPeersList || !discoveredPeersCount) return;
|
|
1732
|
+
|
|
1733
|
+
const discoveredPeers = this.mesh.getDiscoveredPeers();
|
|
1734
|
+
const connectedPeerIds = this.mesh.getPeers().map(p => p.peerId);
|
|
1735
|
+
|
|
1736
|
+
// Filter out already connected peers
|
|
1737
|
+
const availablePeers = discoveredPeers.filter(peer =>
|
|
1738
|
+
!connectedPeerIds.includes(peer.peerId) && peer.peerId !== this.mesh.peerId
|
|
1739
|
+
);
|
|
1740
|
+
|
|
1741
|
+
discoveredPeersCount.textContent = availablePeers.length;
|
|
1742
|
+
|
|
1743
|
+
if (availablePeers.length === 0) {
|
|
1744
|
+
discoveredPeersList.innerHTML = '<p class="empty-state">No peers discovered</p>';
|
|
1745
|
+
return;
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
discoveredPeersList.innerHTML = availablePeers.map(peer => {
|
|
1749
|
+
const lastSeen = peer.lastSeen
|
|
1750
|
+
? `${Math.round((Date.now() - peer.lastSeen) / 1000)}s ago`
|
|
1751
|
+
: 'Unknown';
|
|
1752
|
+
|
|
1753
|
+
return `
|
|
1754
|
+
<div class="peer-item discovered">
|
|
1755
|
+
<div class="peer-info">
|
|
1756
|
+
<span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
|
|
1757
|
+
<button class="btn small" data-peer-id="${peer.peerId}" onclick="window.peerPigeonUI.connectToPeerFromButton(this)">
|
|
1758
|
+
Connect
|
|
1759
|
+
</button>
|
|
1760
|
+
</div>
|
|
1761
|
+
<div class="peer-details">
|
|
1762
|
+
<small>Last seen: ${lastSeen}</small>
|
|
1763
|
+
<small>Distance: ${peer.distance || 'Unknown'}</small>
|
|
1764
|
+
</div>
|
|
1765
|
+
</div>
|
|
1766
|
+
`;
|
|
1767
|
+
}).join('');
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
updateSettings() {
|
|
1771
|
+
// Update form values to match mesh state
|
|
1772
|
+
const minPeersInput = document.getElementById('min-peers');
|
|
1773
|
+
const maxPeersInput = document.getElementById('max-peers');
|
|
1774
|
+
const autoDiscoveryToggle = document.getElementById('auto-discovery-toggle');
|
|
1775
|
+
const evictionStrategyToggle = document.getElementById('eviction-strategy-toggle');
|
|
1776
|
+
const xorRoutingToggle = document.getElementById('xor-routing-toggle');
|
|
1777
|
+
const webdhtToggle = document.getElementById('webdht-toggle');
|
|
1778
|
+
|
|
1779
|
+
if (minPeersInput) minPeersInput.value = this.mesh.minPeers;
|
|
1780
|
+
if (maxPeersInput) maxPeersInput.value = this.mesh.maxPeers;
|
|
1781
|
+
if (autoDiscoveryToggle) autoDiscoveryToggle.checked = this.mesh.autoDiscovery;
|
|
1782
|
+
if (evictionStrategyToggle) evictionStrategyToggle.checked = this.mesh.evictionStrategy;
|
|
1783
|
+
if (xorRoutingToggle) xorRoutingToggle.checked = this.mesh.xorRouting;
|
|
1784
|
+
|
|
1785
|
+
// Update WebDHT status (read-only)
|
|
1786
|
+
if (webdhtToggle) {
|
|
1787
|
+
const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
|
|
1788
|
+
webdhtToggle.checked = isDHTEnabled;
|
|
1789
|
+
|
|
1790
|
+
// Update the visual styling based on status
|
|
1791
|
+
const parent = webdhtToggle.closest('.auto-discovery-control');
|
|
1792
|
+
if (parent) {
|
|
1793
|
+
if (isDHTEnabled) {
|
|
1794
|
+
parent.style.opacity = '1';
|
|
1795
|
+
parent.title = 'WebDHT is enabled and running';
|
|
1796
|
+
} else {
|
|
1797
|
+
parent.style.opacity = '0.6';
|
|
1798
|
+
parent.title = 'WebDHT is disabled (restart required to enable)';
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
/**
|
|
1805
|
+
* Add a message to the UI message log
|
|
1806
|
+
* @param {string} sender - Message sender identifier
|
|
1807
|
+
* @param {string} content - Message content
|
|
1808
|
+
* @param {string} type - Message type ('info', 'error', 'warning', 'own', 'dm')
|
|
1809
|
+
*/
|
|
1810
|
+
addMessage(sender, content, type = 'info') {
|
|
1811
|
+
// System messages go to the system-messages container (below connection buttons)
|
|
1812
|
+
// Chat messages go to the messages-log container (at the bottom)
|
|
1813
|
+
if (sender === 'System') {
|
|
1814
|
+
this.addSystemMessage(content, type);
|
|
1815
|
+
} else {
|
|
1816
|
+
this.addChatMessage(sender, content, type);
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
/**
|
|
1821
|
+
* Add a system message to the system messages container below connection buttons
|
|
1822
|
+
* @param {string} content - Message content
|
|
1823
|
+
* @param {string} type - Message type ('info', 'error', 'warning')
|
|
1824
|
+
*/
|
|
1825
|
+
addSystemMessage(content, type = 'info') {
|
|
1826
|
+
const systemMessages = document.getElementById('system-messages');
|
|
1827
|
+
if (!systemMessages) return;
|
|
1828
|
+
|
|
1829
|
+
const messageElement = document.createElement('div');
|
|
1830
|
+
messageElement.className = `system-message ${type}`;
|
|
1831
|
+
|
|
1832
|
+
const timestamp = new Date().toLocaleTimeString();
|
|
1833
|
+
|
|
1834
|
+
messageElement.innerHTML = `
|
|
1835
|
+
<div class="system-message-header">
|
|
1836
|
+
<span class="system-message-time">${timestamp}</span>
|
|
1837
|
+
<span class="system-message-type">${type.toUpperCase()}</span>
|
|
1838
|
+
</div>
|
|
1839
|
+
<div class="system-message-content">${content}</div>
|
|
1840
|
+
`;
|
|
1841
|
+
|
|
1842
|
+
systemMessages.appendChild(messageElement);
|
|
1843
|
+
systemMessages.scrollTop = systemMessages.scrollHeight;
|
|
1844
|
+
|
|
1845
|
+
// Limit message history to prevent memory issues
|
|
1846
|
+
const messages = systemMessages.children;
|
|
1847
|
+
if (messages.length > 50) {
|
|
1848
|
+
systemMessages.removeChild(messages[0]);
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
/**
|
|
1853
|
+
* Add a chat message to the messages log at the bottom
|
|
1854
|
+
* @param {string} sender - Message sender identifier
|
|
1855
|
+
* @param {string} content - Message content
|
|
1856
|
+
* @param {string} type - Message type ('own', 'dm')
|
|
1857
|
+
*/
|
|
1858
|
+
addChatMessage(sender, content, type = 'info') {
|
|
1859
|
+
const messagesLog = document.getElementById('messages-log');
|
|
1860
|
+
if (!messagesLog) return;
|
|
1861
|
+
|
|
1862
|
+
const messageElement = document.createElement('div');
|
|
1863
|
+
messageElement.className = `message-item ${type}`;
|
|
1864
|
+
|
|
1865
|
+
const timestamp = new Date().toLocaleTimeString();
|
|
1866
|
+
const senderDisplay = sender === 'You' ? 'You' : sender.substring(0, 3);
|
|
1867
|
+
|
|
1868
|
+
messageElement.innerHTML = `
|
|
1869
|
+
<div class="avatar">${senderDisplay}</div>
|
|
1870
|
+
<div class="message-body">
|
|
1871
|
+
<div class="message-header">
|
|
1872
|
+
${sender} • ${timestamp}
|
|
1873
|
+
</div>
|
|
1874
|
+
<div class="message-content">${content}</div>
|
|
1875
|
+
</div>
|
|
1876
|
+
`;
|
|
1877
|
+
|
|
1878
|
+
messagesLog.appendChild(messageElement);
|
|
1879
|
+
messagesLog.scrollTop = messagesLog.scrollHeight;
|
|
1880
|
+
|
|
1881
|
+
// Limit message history to prevent memory issues
|
|
1882
|
+
const messages = messagesLog.children;
|
|
1883
|
+
if (messages.length > 100) {
|
|
1884
|
+
messagesLog.removeChild(messages[0]);
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
/**
|
|
1889
|
+
* Add an entry to the DHT log
|
|
1890
|
+
* @param {string} message - The log message
|
|
1891
|
+
*/
|
|
1892
|
+
addDHTLogEntry(message) {
|
|
1893
|
+
const dhtLog = document.getElementById('dht-log');
|
|
1894
|
+
if (!dhtLog) return;
|
|
1895
|
+
|
|
1896
|
+
const logEntry = document.createElement('div');
|
|
1897
|
+
logEntry.className = 'dht-log-entry';
|
|
1898
|
+
|
|
1899
|
+
const timestamp = new Date().toLocaleTimeString();
|
|
1900
|
+
logEntry.innerHTML = `
|
|
1901
|
+
<span class="dht-log-time">${timestamp}</span>
|
|
1902
|
+
<span class="dht-log-message">${message}</span>
|
|
1903
|
+
`;
|
|
1904
|
+
|
|
1905
|
+
dhtLog.appendChild(logEntry);
|
|
1906
|
+
dhtLog.scrollTop = dhtLog.scrollHeight;
|
|
1907
|
+
|
|
1908
|
+
// Limit log entries to prevent memory issues
|
|
1909
|
+
const entries = dhtLog.children;
|
|
1910
|
+
if (entries.length > 100) {
|
|
1911
|
+
dhtLog.removeChild(entries[0]);
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
/**
|
|
1916
|
+
* Update the DHT status display
|
|
1917
|
+
*/
|
|
1918
|
+
updateDHTStatus() {
|
|
1919
|
+
const dhtStatusElement = document.getElementById('dht-status');
|
|
1920
|
+
if (!dhtStatusElement) return;
|
|
1921
|
+
|
|
1922
|
+
const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
|
|
1923
|
+
dhtStatusElement.textContent = isDHTEnabled ? 'Enabled' : 'Disabled';
|
|
1924
|
+
dhtStatusElement.className = `status ${isDHTEnabled ? 'connected' : 'disconnected'}`;
|
|
1925
|
+
}
|
|
1926
|
+
}
|