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.
@@ -1,1719 +1,2105 @@
1
1
  // Updated: 2025-07-04 - Fixed getConnectionStatus method name
2
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
- });
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
+ // Crypto event listeners
80
+ this.mesh.addEventListener('cryptoReady', (_data) => {
81
+ this.addMessage('System', '🔐 Crypto initialized successfully', 'success');
82
+ this.updateCryptoStatus();
83
+ });
84
+
85
+ this.mesh.addEventListener('cryptoError', (data) => {
86
+ this.addMessage('System', `🔐 Crypto error: ${data.error}`, 'error');
87
+ this.addCryptoTestResult(`❌ Crypto Error: ${data.error}`, 'error');
88
+ });
89
+
90
+ this.mesh.addEventListener('peerKeyAdded', (data) => {
91
+ this.addMessage('System', `🔐 Public key received from ${data.peerId.substring(0, 8)}...`);
92
+ this.updateCryptoStatus();
93
+ });
94
+
95
+ this.mesh.addEventListener('userAuthenticated', (data) => {
96
+ this.addMessage('System', `🔐 Authenticated as ${data.alias}`, 'success');
97
+ this.updateCryptoStatus();
98
+ });
99
+ }
100
+
101
+ handleStatusChange(data) {
102
+ switch (data.type) {
103
+ case 'initialized':
104
+ this.updateUI();
105
+ break;
106
+ case 'connecting':
107
+ this.addMessage('System', 'Connecting to signaling server...');
108
+ this.updateUI();
109
+ break;
110
+ case 'connected':
111
+ this.addMessage('System', 'Connected to signaling server');
112
+ this.updateUI();
113
+ break;
114
+ case 'disconnected':
115
+ this.addMessage('System', 'Disconnected from signaling server');
116
+ this.updateUI();
117
+ this.updateDiscoveredPeers();
118
+ break;
119
+ case 'error':
120
+ this.addMessage('System', data.message, 'error');
121
+ this.updateUI();
122
+ break;
123
+ case 'warning':
124
+ this.addMessage('System', data.message, 'warning');
125
+ break;
126
+ case 'info':
127
+ this.addMessage('System', data.message);
128
+ break;
129
+ case 'urlLoaded':
130
+ document.getElementById('signaling-url').value = data.signalingUrl;
131
+ this.addMessage('System', `API Gateway URL loaded: ${data.signalingUrl}`);
132
+ break;
133
+ case 'setting': {
134
+ const settingName = data.setting === 'autoDiscovery'
135
+ ? 'Auto discovery'
136
+ : data.setting === 'evictionStrategy'
137
+ ? 'Smart eviction strategy'
138
+ : data.setting === 'xorRouting'
139
+ ? 'XOR-based routing'
140
+ : data.setting === 'connectionType' ? 'Connection type' : data.setting;
141
+
142
+ if (data.setting === 'connectionType') {
143
+ this.addMessage('System', `${settingName} set to: ${data.value}`);
144
+ } else {
145
+ this.addMessage('System', `${settingName} ${data.value ? 'enabled' : 'disabled'}`);
146
+ }
147
+ break;
148
+ }
149
+ }
150
+ }
151
+
152
+ bindDOMEvents() {
153
+ // Connection controls
154
+ document.getElementById('connect-btn').addEventListener('click', () => {
155
+ this.handleConnect();
156
+ });
157
+
158
+ document.getElementById('disconnect-btn').addEventListener('click', () => {
159
+ this.handleDisconnect();
160
+ });
161
+
162
+ document.getElementById('cleanup-btn').addEventListener('click', () => {
163
+ this.handleCleanup();
164
+ });
165
+
166
+ document.getElementById('health-check-btn').addEventListener('click', () => {
167
+ this.handleHealthCheck();
168
+ });
169
+
170
+ document.getElementById('refresh-btn').addEventListener('click', () => {
171
+ window.location.reload();
172
+ });
173
+
174
+ // Messaging
175
+ document.getElementById('send-message-btn').addEventListener('click', () => {
176
+ this.sendMessage();
177
+ });
178
+
179
+ document.getElementById('message-input').addEventListener('keypress', (e) => {
180
+ if (e.key === 'Enter') {
181
+ this.sendMessage();
182
+ }
183
+ });
184
+
185
+ // Manual connection
186
+ document.getElementById('connect-peer-btn').addEventListener('click', () => {
187
+ this.connectToPeer();
188
+ });
189
+
190
+ document.getElementById('target-peer').addEventListener('keypress', (e) => {
191
+ if (e.key === 'Enter') {
192
+ this.connectToPeer();
193
+ }
194
+ });
195
+
196
+ // Settings
197
+ document.getElementById('min-peers').addEventListener('change', (e) => {
198
+ this.mesh.setMinPeers(parseInt(e.target.value));
199
+ });
200
+
201
+ document.getElementById('max-peers').addEventListener('change', (e) => {
202
+ this.mesh.setMaxPeers(parseInt(e.target.value));
203
+ });
204
+
205
+ document.getElementById('auto-discovery-toggle').addEventListener('change', (e) => {
206
+ this.mesh.setAutoDiscovery(e.target.checked);
207
+ });
208
+
209
+ document.getElementById('eviction-strategy-toggle').addEventListener('change', (e) => {
210
+ this.mesh.setEvictionStrategy(e.target.checked);
211
+ });
212
+
213
+ document.getElementById('xor-routing-toggle').addEventListener('change', (e) => {
214
+ this.mesh.setXorRouting(e.target.checked);
215
+ });
216
+
217
+ // DHT controls
218
+ this.setupDHTControls();
219
+
220
+ // Crypto controls
221
+ this.setupCryptoControls();
222
+
223
+ // Collapsible sections
224
+ this.setupCollapsibleSections();
225
+
226
+ // Media controls
227
+ this.setupMediaControls();
228
+ }
229
+
230
+ setupDHTControls() {
231
+ // DHT input fields and controls
232
+ const dhtKey = document.getElementById('dht-key');
233
+ const dhtValue = document.getElementById('dht-value');
234
+ const dhtGetKey = document.getElementById('dht-get-key'); // Separate key field for retrieval
235
+ const dhtPutBtn = document.getElementById('dht-put-btn');
236
+ const dhtUpdateBtn = document.getElementById('dht-update-btn');
237
+ const dhtGetBtn = document.getElementById('dht-get-btn');
238
+ const dhtSubscribeBtn = document.getElementById('dht-subscribe-btn');
239
+ const dhtUnsubscribeBtn = document.getElementById('dht-unsubscribe-btn');
240
+ const dhtEnableTtl = document.getElementById('dht-enable-ttl');
241
+ const dhtTtlGroup = document.getElementById('dht-ttl-group');
242
+ const dhtTtl = document.getElementById('dht-ttl');
243
+
244
+ // Debug: Check if elements are found
245
+ console.log('DHT Controls setup - Elements found:', {
246
+ dhtKey: !!dhtKey,
247
+ dhtValue: !!dhtValue,
248
+ dhtGetKey: !!dhtGetKey,
249
+ dhtPutBtn: !!dhtPutBtn,
250
+ dhtUpdateBtn: !!dhtUpdateBtn,
251
+ dhtGetBtn: !!dhtGetBtn,
252
+ dhtSubscribeBtn: !!dhtSubscribeBtn,
253
+ dhtUnsubscribeBtn: !!dhtUnsubscribeBtn
254
+ });
255
+
256
+ if (!dhtKey) {
257
+ console.error('DHT key input element not found!');
258
+ this.addDHTLogEntry('❌ Error: DHT key input field not found in DOM');
259
+ }
46
260
 
47
- this.mesh.addEventListener('peersUpdated', () => {
48
- this.updateDiscoveredPeers();
49
- });
261
+ if (!dhtValue) {
262
+ console.error('DHT value input element not found!');
263
+ this.addDHTLogEntry('❌ Error: DHT value input field not found in DOM');
264
+ }
50
265
 
51
- this.mesh.addEventListener('connectionStats', (stats) => {
52
- // Handle connection stats if needed
53
- });
266
+ if (!dhtGetKey) {
267
+ console.error('DHT get-key input element not found!');
268
+ this.addDHTLogEntry('❌ Error: DHT get-key input field not found in DOM');
269
+ }
54
270
 
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
- });
271
+ // Toggle TTL input visibility
272
+ if (dhtEnableTtl && dhtTtlGroup) {
273
+ dhtEnableTtl.addEventListener('change', (e) => {
274
+ dhtTtlGroup.style.display = e.target.checked ? 'block' : 'none';
275
+ });
276
+ }
60
277
 
61
- // Media event listeners
62
- this.mesh.addEventListener('localStreamStarted', (data) => {
63
- this.handleLocalStreamStarted(data);
278
+ // Store in DHT
279
+ if (dhtPutBtn) {
280
+ dhtPutBtn.addEventListener('click', async () => {
281
+ const key = dhtKey?.value?.trim();
282
+ const value = dhtValue?.value?.trim();
283
+
284
+ // Debug logging
285
+ console.log('DHT PUT - Elements found:', {
286
+ dhtKey: !!dhtKey,
287
+ dhtValue: !!dhtValue,
288
+ keyValue: key,
289
+ valueValue: value
64
290
  });
65
291
 
66
- this.mesh.addEventListener('localStreamStopped', () => {
67
- this.handleLocalStreamStopped();
68
- });
292
+ if (!key || !value) {
293
+ this.addDHTLogEntry('❌ Error: Both key and value are required');
294
+ this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
295
+ return;
296
+ }
69
297
 
70
- this.mesh.addEventListener('mediaError', (data) => {
71
- this.addMessage('System', `Media error: ${data.error.message}`, 'error');
72
- });
298
+ if (!this.mesh.isDHTEnabled()) {
299
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
300
+ return;
301
+ }
73
302
 
74
- // Listen for remote streams
75
- this.mesh.addEventListener('remoteStream', (data) => {
76
- this.handleRemoteStream(data);
77
- });
78
- }
303
+ try {
304
+ let parsedValue;
305
+ try {
306
+ parsedValue = JSON.parse(value);
307
+ } catch {
308
+ parsedValue = value; // Use as string if not valid JSON
309
+ }
310
+
311
+ const options = {};
312
+ if (dhtEnableTtl?.checked && dhtTtl?.value) {
313
+ options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
314
+ }
315
+
316
+ const success = await this.mesh.dhtPut(key, parsedValue, options);
317
+ if (success) {
318
+ this.addDHTLogEntry(`✅ Stored: ${key} = ${JSON.stringify(parsedValue)}`);
319
+ if (options.ttl) {
320
+ this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
321
+ }
322
+ this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
79
323
 
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' ? 'Auto discovery' :
114
- data.setting === 'evictionStrategy' ? 'Smart eviction strategy' :
115
- data.setting === 'xorRouting' ? 'XOR-based routing' :
116
- data.setting === 'connectionType' ? 'Connection type' : data.setting;
117
-
118
- if (data.setting === 'connectionType') {
119
- this.addMessage('System', `${settingName} set to: ${data.value}`);
120
- } else {
121
- this.addMessage('System', `${settingName} ${data.value ? 'enabled' : 'disabled'}`);
122
- }
123
- break;
324
+ // Auto-subscribe to the key we just stored (essential for original storing peers)
325
+ try {
326
+ await this.mesh.dhtSubscribe(key);
327
+ this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
328
+ this.addDHTLogEntry(' 📡 Will receive and relay all future updates for this key');
329
+ } catch (subscribeError) {
330
+ this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
331
+ }
332
+ } else {
333
+ this.addDHTLogEntry(`❌ Failed to store: ${key}`);
334
+ }
335
+ } catch (error) {
336
+ this.addDHTLogEntry(`❌ Error storing ${key}: ${error.message}`);
124
337
  }
338
+ });
125
339
  }
126
340
 
127
- bindDOMEvents() {
128
- // Connection controls
129
- document.getElementById('connect-btn').addEventListener('click', () => {
130
- this.handleConnect();
341
+ // Update in DHT
342
+ if (dhtUpdateBtn) {
343
+ dhtUpdateBtn.addEventListener('click', async () => {
344
+ const key = dhtKey?.value?.trim();
345
+ const value = dhtValue?.value?.trim();
346
+
347
+ // Debug logging
348
+ console.log('DHT UPDATE - Elements found:', {
349
+ dhtKey: !!dhtKey,
350
+ dhtValue: !!dhtValue,
351
+ keyValue: key,
352
+ valueValue: value
131
353
  });
132
354
 
133
- document.getElementById('disconnect-btn').addEventListener('click', () => {
134
- this.handleDisconnect();
135
- });
136
-
137
- document.getElementById('cleanup-btn').addEventListener('click', () => {
138
- this.handleCleanup();
139
- });
140
-
141
- document.getElementById('health-check-btn').addEventListener('click', () => {
142
- this.handleHealthCheck();
143
- });
144
-
145
- document.getElementById('refresh-btn').addEventListener('click', () => {
146
- window.location.reload();
147
- });
355
+ if (!key || !value) {
356
+ this.addDHTLogEntry('❌ Error: Both key and value are required');
357
+ this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
358
+ return;
359
+ }
148
360
 
149
- // Messaging
150
- document.getElementById('send-message-btn').addEventListener('click', () => {
151
- this.sendMessage();
152
- });
361
+ if (!this.mesh.isDHTEnabled()) {
362
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
363
+ return;
364
+ }
153
365
 
154
- document.getElementById('message-input').addEventListener('keypress', (e) => {
155
- if (e.key === 'Enter') {
156
- this.sendMessage();
366
+ try {
367
+ let parsedValue;
368
+ try {
369
+ parsedValue = JSON.parse(value);
370
+ } catch {
371
+ parsedValue = value; // Use as string if not valid JSON
372
+ }
373
+
374
+ const options = {};
375
+ if (dhtEnableTtl?.checked && dhtTtl?.value) {
376
+ options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
377
+ }
378
+
379
+ const success = await this.mesh.dhtUpdate(key, parsedValue, options);
380
+ if (success) {
381
+ this.addDHTLogEntry(`🔄 Updated: ${key} = ${JSON.stringify(parsedValue)}`);
382
+ if (options.ttl) {
383
+ this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
157
384
  }
158
- });
385
+ this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
159
386
 
160
- // Manual connection
161
- document.getElementById('connect-peer-btn').addEventListener('click', () => {
162
- this.connectToPeer();
163
- });
164
-
165
- document.getElementById('target-peer').addEventListener('keypress', (e) => {
166
- if (e.key === 'Enter') {
167
- this.connectToPeer();
387
+ // Auto-subscribe to the key we just updated (essential for original storing peers)
388
+ try {
389
+ await this.mesh.dhtSubscribe(key);
390
+ this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
391
+ this.addDHTLogEntry(' 📡 Will receive and relay all future updates for this key');
392
+ } catch (subscribeError) {
393
+ this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
168
394
  }
169
- });
395
+ } else {
396
+ this.addDHTLogEntry(`❌ Failed to update: ${key}`);
397
+ }
398
+ } catch (error) {
399
+ this.addDHTLogEntry(`❌ Error updating ${key}: ${error.message}`);
400
+ }
401
+ });
402
+ }
170
403
 
171
- // Settings
172
- document.getElementById('min-peers').addEventListener('change', (e) => {
173
- this.mesh.setMinPeers(parseInt(e.target.value));
174
- });
404
+ // Get from DHT
405
+ if (dhtGetBtn) {
406
+ dhtGetBtn.addEventListener('click', async () => {
407
+ const key = dhtGetKey?.value?.trim(); // Fixed: Use dhtGetKey instead of dhtKey
175
408
 
176
- document.getElementById('max-peers').addEventListener('change', (e) => {
177
- this.mesh.setMaxPeers(parseInt(e.target.value));
409
+ // Debug logging
410
+ console.log('DHT GET - Elements found:', {
411
+ dhtGetKey: !!dhtGetKey,
412
+ keyValue: key
178
413
  });
179
414
 
180
- document.getElementById('auto-discovery-toggle').addEventListener('change', (e) => {
181
- this.mesh.setAutoDiscovery(e.target.checked);
182
- });
415
+ if (!key) {
416
+ this.addDHTLogEntry('❌ Error: Key is required');
417
+ this.addDHTLogEntry(` Debug: key="${key}"`);
418
+ return;
419
+ }
183
420
 
184
- document.getElementById('eviction-strategy-toggle').addEventListener('change', (e) => {
185
- this.mesh.setEvictionStrategy(e.target.checked);
186
- });
421
+ if (!this.mesh.isDHTEnabled()) {
422
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
423
+ return;
424
+ }
187
425
 
188
- document.getElementById('xor-routing-toggle').addEventListener('change', (e) => {
189
- this.mesh.setXorRouting(e.target.checked);
190
- });
426
+ try {
427
+ this.addDHTLogEntry(`🔍 Fetching from ORIGINAL STORING PEERS: ${key}`);
428
+ this.addDHTLogEntry(' 📡 Bypassing local cache to ensure fresh data');
429
+
430
+ // Force fresh retrieval from original storing peers
431
+ const value = await this.mesh.dhtGet(key, { forceRefresh: true });
432
+ if (value !== null) {
433
+ this.addDHTLogEntry(`📥 Retrieved from original peers: ${key} = ${JSON.stringify(value)}`);
434
+ this.addDHTLogEntry(' ✅ Data is FRESH from authoritative source');
435
+ if (dhtValue) {
436
+ dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
437
+ }
191
438
 
192
- // DHT controls
193
- this.setupDHTControls();
194
-
195
- // Collapsible sections
196
- this.setupCollapsibleSections();
197
-
198
- // Media controls
199
- this.setupMediaControls();
200
- }
201
-
202
- setupDHTControls() {
203
- // DHT input fields and controls
204
- const dhtKey = document.getElementById('dht-key');
205
- const dhtValue = document.getElementById('dht-value');
206
- const dhtGetKey = document.getElementById('dht-get-key'); // Separate key field for retrieval
207
- const dhtPutBtn = document.getElementById('dht-put-btn');
208
- const dhtUpdateBtn = document.getElementById('dht-update-btn');
209
- const dhtGetBtn = document.getElementById('dht-get-btn');
210
- const dhtSubscribeBtn = document.getElementById('dht-subscribe-btn');
211
- const dhtUnsubscribeBtn = document.getElementById('dht-unsubscribe-btn');
212
- const dhtEnableTtl = document.getElementById('dht-enable-ttl');
213
- const dhtTtlGroup = document.getElementById('dht-ttl-group');
214
- const dhtTtl = document.getElementById('dht-ttl');
215
-
216
- // Debug: Check if elements are found
217
- console.log('DHT Controls setup - Elements found:', {
218
- dhtKey: !!dhtKey,
219
- dhtValue: !!dhtValue,
220
- dhtGetKey: !!dhtGetKey,
221
- dhtPutBtn: !!dhtPutBtn,
222
- dhtUpdateBtn: !!dhtUpdateBtn,
223
- dhtGetBtn: !!dhtGetBtn,
224
- dhtSubscribeBtn: !!dhtSubscribeBtn,
225
- dhtUnsubscribeBtn: !!dhtUnsubscribeBtn
226
- });
227
-
228
- if (!dhtKey) {
229
- console.error('DHT key input element not found!');
230
- this.addDHTLogEntry('❌ Error: DHT key input field not found in DOM');
439
+ // Auto-subscribe to the key we just retrieved for future updates
440
+ try {
441
+ await this.mesh.dhtSubscribe(key);
442
+ this.addDHTLogEntry(`🔔 Auto-subscribed for future updates: ${key}`);
443
+ this.addDHTLogEntry(' 📡 Will receive notifications when original peers update this key');
444
+ } catch (subscribeError) {
445
+ this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
446
+ }
447
+ } else {
448
+ this.addDHTLogEntry(`❌ Not found on original storing peers: ${key}`);
449
+ this.addDHTLogEntry(' 💡 Key may not exist or all original storing peers are offline');
450
+ }
451
+ } catch (error) {
452
+ this.addDHTLogEntry(`❌ Error retrieving ${key}: ${error.message}`);
231
453
  }
232
-
233
- if (!dhtValue) {
234
- console.error('DHT value input element not found!');
235
- this.addDHTLogEntry('❌ Error: DHT value input field not found in DOM');
454
+ });
455
+ }
456
+
457
+ // Subscribe to DHT key
458
+ if (dhtSubscribeBtn) {
459
+ dhtSubscribeBtn.addEventListener('click', async () => {
460
+ // Check both key fields - use whichever has a value
461
+ const putKey = dhtKey?.value?.trim();
462
+ const getKey = dhtGetKey?.value?.trim();
463
+ const key = putKey || getKey;
464
+
465
+ if (!key) {
466
+ this.addDHTLogEntry('❌ Error: Key is required (enter key in either Put/Update or Get field)');
467
+ return;
236
468
  }
237
-
238
- if (!dhtGetKey) {
239
- console.error('DHT get-key input element not found!');
240
- this.addDHTLogEntry('❌ Error: DHT get-key input field not found in DOM');
469
+
470
+ if (!this.mesh.isDHTEnabled()) {
471
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
472
+ return;
241
473
  }
242
474
 
243
- // Toggle TTL input visibility
244
- if (dhtEnableTtl && dhtTtlGroup) {
245
- dhtEnableTtl.addEventListener('change', (e) => {
246
- dhtTtlGroup.style.display = e.target.checked ? 'block' : 'none';
247
- });
475
+ try {
476
+ this.addDHTLogEntry(`🔔 Explicitly subscribing to key: ${key}`);
477
+ this.addDHTLogEntry(' 📡 Will receive notifications when original storing peers update this key');
478
+
479
+ const value = await this.mesh.dhtSubscribe(key);
480
+ this.addDHTLogEntry(`✅ Subscribed to: ${key}`);
481
+ if (value !== null) {
482
+ this.addDHTLogEntry(` Current value from original storing peers: ${JSON.stringify(value)}`);
483
+ if (dhtValue) {
484
+ dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
485
+ }
486
+ } else {
487
+ this.addDHTLogEntry(' No current value found on original storing peers');
488
+ }
489
+ } catch (error) {
490
+ this.addDHTLogEntry(`❌ Error subscribing to ${key}: ${error.message}`);
248
491
  }
492
+ });
493
+ }
249
494
 
250
- // Store in DHT
251
- if (dhtPutBtn) {
252
- dhtPutBtn.addEventListener('click', async () => {
253
- const key = dhtKey?.value?.trim();
254
- const value = dhtValue?.value?.trim();
255
-
256
- // Debug logging
257
- console.log('DHT PUT - Elements found:', {
258
- dhtKey: !!dhtKey,
259
- dhtValue: !!dhtValue,
260
- keyValue: key,
261
- valueValue: value
262
- });
263
-
264
- if (!key || !value) {
265
- this.addDHTLogEntry('❌ Error: Both key and value are required');
266
- this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
267
- return;
268
- }
269
-
270
- if (!this.mesh.isDHTEnabled()) {
271
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
272
- return;
273
- }
274
-
275
- try {
276
- let parsedValue;
277
- try {
278
- parsedValue = JSON.parse(value);
279
- } catch {
280
- parsedValue = value; // Use as string if not valid JSON
281
- }
282
-
283
- const options = {};
284
- if (dhtEnableTtl?.checked && dhtTtl?.value) {
285
- options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
286
- }
287
-
288
- const success = await this.mesh.dhtPut(key, parsedValue, options);
289
- if (success) {
290
- this.addDHTLogEntry(`✅ Stored: ${key} = ${JSON.stringify(parsedValue)}`);
291
- if (options.ttl) {
292
- this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
293
- }
294
- this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
295
-
296
- // Auto-subscribe to the key we just stored (essential for original storing peers)
297
- try {
298
- await this.mesh.dhtSubscribe(key);
299
- this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
300
- this.addDHTLogEntry(` 📡 Will receive and relay all future updates for this key`);
301
- } catch (subscribeError) {
302
- this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
303
- }
304
- } else {
305
- this.addDHTLogEntry(`❌ Failed to store: ${key}`);
306
- }
307
- } catch (error) {
308
- this.addDHTLogEntry(`❌ Error storing ${key}: ${error.message}`);
309
- }
310
- });
495
+ // Unsubscribe from DHT key
496
+ if (dhtUnsubscribeBtn) {
497
+ dhtUnsubscribeBtn.addEventListener('click', async () => {
498
+ // Check both key fields - use whichever has a value
499
+ const putKey = dhtKey?.value?.trim();
500
+ const getKey = dhtGetKey?.value?.trim();
501
+ const key = putKey || getKey;
502
+
503
+ if (!key) {
504
+ this.addDHTLogEntry('❌ Error: Key is required (enter key in either Put/Update or Get field)');
505
+ return;
311
506
  }
312
507
 
313
- // Update in DHT
314
- if (dhtUpdateBtn) {
315
- dhtUpdateBtn.addEventListener('click', async () => {
316
- const key = dhtKey?.value?.trim();
317
- const value = dhtValue?.value?.trim();
318
-
319
- // Debug logging
320
- console.log('DHT UPDATE - Elements found:', {
321
- dhtKey: !!dhtKey,
322
- dhtValue: !!dhtValue,
323
- keyValue: key,
324
- valueValue: value
325
- });
326
-
327
- if (!key || !value) {
328
- this.addDHTLogEntry('❌ Error: Both key and value are required');
329
- this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
330
- return;
331
- }
332
-
333
- if (!this.mesh.isDHTEnabled()) {
334
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
335
- return;
336
- }
337
-
338
- try {
339
- let parsedValue;
340
- try {
341
- parsedValue = JSON.parse(value);
342
- } catch {
343
- parsedValue = value; // Use as string if not valid JSON
344
- }
345
-
346
- const options = {};
347
- if (dhtEnableTtl?.checked && dhtTtl?.value) {
348
- options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
349
- }
350
-
351
- const success = await this.mesh.dhtUpdate(key, parsedValue, options);
352
- if (success) {
353
- this.addDHTLogEntry(`🔄 Updated: ${key} = ${JSON.stringify(parsedValue)}`);
354
- if (options.ttl) {
355
- this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
356
- }
357
- this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
358
-
359
- // Auto-subscribe to the key we just updated (essential for original storing peers)
360
- try {
361
- await this.mesh.dhtSubscribe(key);
362
- this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
363
- this.addDHTLogEntry(` 📡 Will receive and relay all future updates for this key`);
364
- } catch (subscribeError) {
365
- this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
366
- }
367
- } else {
368
- this.addDHTLogEntry(`❌ Failed to update: ${key}`);
369
- }
370
- } catch (error) {
371
- this.addDHTLogEntry(`❌ Error updating ${key}: ${error.message}`);
372
- }
373
- });
508
+ if (!this.mesh.isDHTEnabled()) {
509
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
510
+ return;
374
511
  }
375
512
 
376
- // Get from DHT
377
- if (dhtGetBtn) {
378
- dhtGetBtn.addEventListener('click', async () => {
379
- const key = dhtGetKey?.value?.trim(); // Fixed: Use dhtGetKey instead of dhtKey
380
-
381
- // Debug logging
382
- console.log('DHT GET - Elements found:', {
383
- dhtGetKey: !!dhtGetKey,
384
- keyValue: key
385
- });
386
-
387
- if (!key) {
388
- this.addDHTLogEntry('❌ Error: Key is required');
389
- this.addDHTLogEntry(` Debug: key="${key}"`);
390
- return;
391
- }
392
-
393
- if (!this.mesh.isDHTEnabled()) {
394
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
395
- return;
396
- }
397
-
398
- try {
399
- this.addDHTLogEntry(`🔍 Fetching from ORIGINAL STORING PEERS: ${key}`);
400
- this.addDHTLogEntry(` 📡 Bypassing local cache to ensure fresh data`);
401
-
402
- // Force fresh retrieval from original storing peers
403
- const value = await this.mesh.dhtGet(key, { forceRefresh: true });
404
- if (value !== null) {
405
- this.addDHTLogEntry(`📥 Retrieved from original peers: ${key} = ${JSON.stringify(value)}`);
406
- this.addDHTLogEntry(` ✅ Data is FRESH from authoritative source`);
407
- if (dhtValue) {
408
- dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
409
- }
410
-
411
- // Auto-subscribe to the key we just retrieved for future updates
412
- try {
413
- await this.mesh.dhtSubscribe(key);
414
- this.addDHTLogEntry(`🔔 Auto-subscribed for future updates: ${key}`);
415
- this.addDHTLogEntry(` 📡 Will receive notifications when original peers update this key`);
416
- } catch (subscribeError) {
417
- this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
418
- }
419
- } else {
420
- this.addDHTLogEntry(`❌ Not found on original storing peers: ${key}`);
421
- this.addDHTLogEntry(` 💡 Key may not exist or all original storing peers are offline`);
422
- }
423
- } catch (error) {
424
- this.addDHTLogEntry(`❌ Error retrieving ${key}: ${error.message}`);
425
- }
426
- });
513
+ try {
514
+ await this.mesh.dhtUnsubscribe(key);
515
+ this.addDHTLogEntry(`🔕 Unsubscribed from: ${key}`);
516
+ } catch (error) {
517
+ this.addDHTLogEntry(`❌ Error unsubscribing from ${key}: ${error.message}`);
518
+ }
519
+ });
520
+ }
521
+ }
522
+
523
+ setupCryptoControls() {
524
+ // Key Management Controls
525
+ const generateBtn = document.getElementById('crypto-generate-btn');
526
+ const resetBtn = document.getElementById('crypto-reset-btn');
527
+ const selfTestBtn = document.getElementById('crypto-self-test-btn');
528
+
529
+ // User Authentication Controls
530
+ const loginBtn = document.getElementById('crypto-login-btn');
531
+ const aliasInput = document.getElementById('crypto-alias');
532
+ const passwordInput = document.getElementById('crypto-password');
533
+
534
+ // Messaging Controls
535
+ const testMessageInput = document.getElementById('crypto-test-message');
536
+ const testPeerInput = document.getElementById('crypto-test-peer');
537
+ const sendEncryptedBtn = document.getElementById('crypto-send-encrypted-btn');
538
+
539
+ // Group Encryption Controls
540
+ const groupIdInput = document.getElementById('crypto-group-id');
541
+ const createGroupBtn = document.getElementById('crypto-create-group-btn');
542
+ const groupMessageInput = document.getElementById('crypto-group-message');
543
+ const groupSelect = document.getElementById('crypto-group-select');
544
+ const sendGroupBtn = document.getElementById('crypto-send-group-btn');
545
+
546
+ // Advanced Controls
547
+ const exportKeyBtn = document.getElementById('crypto-export-key-btn');
548
+ const importPeerKeyBtn = document.getElementById('crypto-import-peer-key-btn');
549
+ const benchmarkBtn = document.getElementById('crypto-benchmark-btn');
550
+
551
+ // Import Form Controls
552
+ const importForm = document.getElementById('crypto-import-form');
553
+ const importPeerIdInput = document.getElementById('crypto-import-peer-id');
554
+ const importPublicKeyInput = document.getElementById('crypto-import-public-key');
555
+ const importConfirmBtn = document.getElementById('crypto-import-confirm-btn');
556
+ const importCancelBtn = document.getElementById('crypto-import-cancel-btn');
557
+
558
+ // Key Management Event Handlers
559
+ if (generateBtn) {
560
+ generateBtn.addEventListener('click', async () => {
561
+ try {
562
+ this.addCryptoTestResult('🔄 Generating new keypair...', 'info');
563
+ await this.mesh.initCrypto({ generateKeypair: true });
564
+ this.addCryptoTestResult('✅ New keypair generated successfully', 'success');
565
+ this.updateCryptoStatus();
566
+ } catch (error) {
567
+ this.addCryptoTestResult(`❌ Failed to generate keypair: ${error.message}`, 'error');
427
568
  }
569
+ });
570
+ }
428
571
 
429
- // Subscribe to DHT key
430
- if (dhtSubscribeBtn) {
431
- dhtSubscribeBtn.addEventListener('click', async () => {
432
- // Check both key fields - use whichever has a value
433
- const putKey = dhtKey?.value?.trim();
434
- const getKey = dhtGetKey?.value?.trim();
435
- const key = putKey || getKey;
436
-
437
- if (!key) {
438
- this.addDHTLogEntry('❌ Error: Key is required (enter key in either Put/Update or Get field)');
439
- return;
440
- }
441
-
442
- if (!this.mesh.isDHTEnabled()) {
443
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
444
- return;
445
- }
446
-
447
- try {
448
- this.addDHTLogEntry(`🔔 Explicitly subscribing to key: ${key}`);
449
- this.addDHTLogEntry(` 📡 Will receive notifications when original storing peers update this key`);
450
-
451
- const value = await this.mesh.dhtSubscribe(key);
452
- this.addDHTLogEntry(`✅ Subscribed to: ${key}`);
453
- if (value !== null) {
454
- this.addDHTLogEntry(` Current value from original storing peers: ${JSON.stringify(value)}`);
455
- if (dhtValue) {
456
- dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
457
- }
458
- } else {
459
- this.addDHTLogEntry(` No current value found on original storing peers`);
460
- }
461
- } catch (error) {
462
- this.addDHTLogEntry(`❌ Error subscribing to ${key}: ${error.message}`);
463
- }
464
- });
572
+ if (resetBtn) {
573
+ resetBtn.addEventListener('click', () => {
574
+ if (confirm('This will clear all crypto keys and reset the crypto system. Continue?')) {
575
+ try {
576
+ this.mesh.resetCrypto();
577
+ this.addCryptoTestResult('✅ Crypto system reset', 'success');
578
+ this.updateCryptoStatus();
579
+ this.clearCryptoTestResults();
580
+ } catch (error) {
581
+ this.addCryptoTestResult(`❌ Failed to reset crypto: ${error.message}`, 'error');
582
+ }
465
583
  }
584
+ });
585
+ }
466
586
 
467
- // Unsubscribe from DHT key
468
- if (dhtUnsubscribeBtn) {
469
- dhtUnsubscribeBtn.addEventListener('click', async () => {
470
- // Check both key fields - use whichever has a value
471
- const putKey = dhtKey?.value?.trim();
472
- const getKey = dhtGetKey?.value?.trim();
473
- const key = putKey || getKey;
474
-
475
- if (!key) {
476
- this.addDHTLogEntry('❌ Error: Key is required (enter key in either Put/Update or Get field)');
477
- return;
478
- }
479
-
480
- if (!this.mesh.isDHTEnabled()) {
481
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
482
- return;
483
- }
484
-
485
- try {
486
- await this.mesh.dhtUnsubscribe(key);
487
- this.addDHTLogEntry(`🔕 Unsubscribed from: ${key}`);
488
- } catch (error) {
489
- this.addDHTLogEntry(`❌ Error unsubscribing from ${key}: ${error.message}`);
490
- }
587
+ if (selfTestBtn) {
588
+ selfTestBtn.addEventListener('click', async () => {
589
+ try {
590
+ this.addCryptoTestResult('🔄 Running crypto self-tests...', 'info');
591
+ const results = await this.mesh.runCryptoTests();
592
+
593
+ // Handle the actual format returned by CryptoManager
594
+ if (results.keypairGeneration !== undefined) {
595
+ const status = results.keypairGeneration ? '✅' : '❌';
596
+ const type = results.keypairGeneration ? 'success' : 'error';
597
+ this.addCryptoTestResult(`${status} keypairGeneration: ${results.keypairGeneration}`, type);
598
+ }
599
+
600
+ if (results.encryption !== undefined) {
601
+ const status = results.encryption ? '✅' : '❌';
602
+ const type = results.encryption ? 'success' : 'error';
603
+ this.addCryptoTestResult(`${status} encryption: ${results.encryption}`, type);
604
+ }
605
+
606
+ if (results.decryption !== undefined) {
607
+ const status = results.decryption ? '✅' : '❌';
608
+ const type = results.decryption ? 'success' : 'error';
609
+ this.addCryptoTestResult(`${status} decryption: ${results.decryption}`, type);
610
+ }
611
+
612
+ if (results.signing !== undefined) {
613
+ const status = results.signing ? '✅' : '❌';
614
+ const type = results.signing ? 'success' : 'error';
615
+ this.addCryptoTestResult(`${status} signing: ${results.signing}`, type);
616
+ }
617
+
618
+ if (results.verification !== undefined) {
619
+ const status = results.verification ? '✅' : '❌';
620
+ const type = results.verification ? 'success' : 'error';
621
+ this.addCryptoTestResult(`${status} verification: ${results.verification}`, type);
622
+ }
623
+
624
+ if (results.groupEncryption !== undefined) {
625
+ const status = results.groupEncryption ? '✅' : '❌';
626
+ const type = results.groupEncryption ? 'success' : 'error';
627
+ this.addCryptoTestResult(`${status} groupEncryption: ${results.groupEncryption}`, type);
628
+ }
629
+
630
+ if (results.errors && results.errors.length > 0) {
631
+ results.errors.forEach(error => {
632
+ this.addCryptoTestResult(`❌ errors: ${error}`, 'error');
491
633
  });
634
+ }
635
+ } catch (error) {
636
+ this.addCryptoTestResult(`❌ Self-test failed: ${error.message}`, 'error');
492
637
  }
638
+ });
493
639
  }
494
640
 
495
- setupMediaControls() {
496
- // Start media button
497
- document.getElementById('start-media-btn').addEventListener('click', async () => {
498
- await this.startMedia();
499
- });
641
+ // User Authentication Event Handlers
642
+ if (loginBtn && aliasInput && passwordInput) {
643
+ loginBtn.addEventListener('click', async () => {
644
+ const alias = aliasInput.value.trim();
645
+ const password = passwordInput.value.trim();
500
646
 
501
- // Stop media button
502
- document.getElementById('stop-media-btn').addEventListener('click', async () => {
503
- await this.stopMedia();
504
- });
505
-
506
- // Toggle video button
507
- document.getElementById('toggle-video-btn').addEventListener('click', () => {
508
- this.toggleVideo();
509
- });
647
+ if (!alias || !password) {
648
+ this.addCryptoTestResult('❌ Both alias and password are required', 'error');
649
+ return;
650
+ }
510
651
 
511
- // Toggle audio button
512
- document.getElementById('toggle-audio-btn').addEventListener('click', () => {
513
- this.toggleAudio();
514
- });
652
+ try {
653
+ this.addCryptoTestResult(`🔄 Authenticating as ${alias}...`, 'info');
654
+ await this.mesh.initCrypto({ alias, password });
655
+ this.addCryptoTestResult(`✅ Authenticated as ${alias}`, 'success');
656
+ this.updateCryptoStatus();
515
657
 
516
- // Audio test button
517
- document.getElementById('test-audio-btn').addEventListener('click', () => {
518
- this.testAudio();
519
- });
658
+ // Clear password for security
659
+ passwordInput.value = '';
660
+ } catch (error) {
661
+ this.addCryptoTestResult(`❌ Authentication failed: ${error.message}`, 'error');
662
+ }
663
+ });
664
+ }
520
665
 
521
- // Media type checkboxes
522
- document.getElementById('enable-video').addEventListener('change', () => {
523
- this.updateMediaButtonStates();
524
- });
666
+ // Messaging Event Handlers
667
+ if (sendEncryptedBtn && testMessageInput && testPeerInput) {
668
+ sendEncryptedBtn.addEventListener('click', async () => {
669
+ const message = testMessageInput.value.trim();
670
+ const peerId = testPeerInput.value.trim();
525
671
 
526
- document.getElementById('enable-audio').addEventListener('change', () => {
527
- this.updateMediaButtonStates();
528
- });
672
+ if (!message) {
673
+ this.addCryptoTestResult('❌ Message is required', 'error');
674
+ return;
675
+ }
529
676
 
530
- // Device selection dropdowns
531
- document.getElementById('camera-select').addEventListener('change', () => {
532
- // Auto-restart media if it's currently active
533
- if (this.mesh.getMediaState().hasLocalStream) {
534
- this.startMedia();
535
- }
536
- });
677
+ if (!peerId) {
678
+ this.addCryptoTestResult('❌ Target peer ID is required', 'error');
679
+ return;
680
+ }
537
681
 
538
- document.getElementById('microphone-select').addEventListener('change', () => {
539
- // Auto-restart media if it's currently active
540
- if (this.mesh.getMediaState().hasLocalStream) {
541
- this.startMedia();
542
- }
543
- });
682
+ try {
683
+ this.addCryptoTestResult(`🔄 Sending encrypted message to ${peerId.substring(0, 8)}...`, 'info');
684
+ await this.mesh.sendEncryptedMessage(peerId, message);
685
+ this.addCryptoTestResult('✅ Encrypted message sent', 'success');
686
+ testMessageInput.value = '';
687
+ } catch (error) {
688
+ this.addCryptoTestResult(`❌ Failed to send encrypted message: ${error.message}`, 'error');
689
+ }
690
+ });
544
691
  }
545
692
 
546
- setupCollapsibleSections() {
547
- const sections = [
548
- 'discovered-peers',
549
- 'connected-peers',
550
- 'manual-connection',
551
- 'settings',
552
- 'dht',
553
- 'media'
554
- ];
555
-
556
- sections.forEach(sectionId => {
557
- const toggle = document.getElementById(`${sectionId}-toggle`);
558
- const content = document.getElementById(`${sectionId}-content`);
559
-
560
- if (toggle && content) {
561
- toggle.addEventListener('click', () => {
562
- this.toggleSection(sectionId);
563
- });
564
- }
565
- });
566
- }
693
+ // Group Encryption Event Handlers
694
+ if (createGroupBtn && groupIdInput) {
695
+ createGroupBtn.addEventListener('click', async () => {
696
+ const groupId = groupIdInput.value.trim();
567
697
 
568
- toggleSection(sectionId) {
569
- const toggle = document.getElementById(`${sectionId}-toggle`);
570
- const content = document.getElementById(`${sectionId}-content`);
571
-
572
- if (!toggle || !content) {
573
- console.warn(`Could not find elements for section: ${sectionId}`);
574
- return;
698
+ if (!groupId) {
699
+ this.addCryptoTestResult('❌ Group ID is required', 'error');
700
+ return;
575
701
  }
576
-
577
- const section = toggle.closest(`.${sectionId}`);
578
-
579
- if (!section) {
580
- console.warn(`Could not find section container for: ${sectionId}`, {
581
- toggle: toggle,
582
- toggleParent: toggle.parentElement,
583
- toggleParentParent: toggle.parentElement?.parentElement,
584
- classList: toggle.parentElement?.parentElement?.classList
585
- });
586
- return;
702
+
703
+ try {
704
+ this.addCryptoTestResult(`🔄 Creating group key for ${groupId}...`, 'info');
705
+ await this.mesh.generateGroupKey(groupId);
706
+ this.addCryptoTestResult(`✅ Group key created for ${groupId}`, 'success');
707
+ this.updateGroupSelect();
708
+ groupIdInput.value = '';
709
+ } catch (error) {
710
+ this.addCryptoTestResult(`❌ Failed to create group key: ${error.message}`, 'error');
587
711
  }
588
-
589
- const isExpanded = toggle.getAttribute('aria-expanded') === 'true';
590
-
591
- toggle.setAttribute('aria-expanded', !isExpanded);
592
-
593
- // Add null check before calling setAttribute
594
- if (section) {
595
- section.setAttribute('aria-expanded', !isExpanded);
712
+ });
713
+ }
714
+
715
+ if (sendGroupBtn && groupMessageInput && groupSelect) {
716
+ sendGroupBtn.addEventListener('click', async () => {
717
+ const message = groupMessageInput.value.trim();
718
+ const groupId = groupSelect.value;
719
+
720
+ if (!message) {
721
+ this.addCryptoTestResult('❌ Group message is required', 'error');
722
+ return;
596
723
  }
597
-
598
- if (isExpanded) {
599
- content.style.display = 'none';
600
- toggle.textContent = toggle.textContent.replace('▼', '▶');
601
- } else {
602
- content.style.display = 'block';
603
- toggle.textContent = toggle.textContent.replace('▶', '▼');
724
+
725
+ if (!groupId) {
726
+ this.addCryptoTestResult('❌ Please select a group', 'error');
727
+ return;
604
728
  }
605
- }
606
729
 
607
- // Media-related methods
608
- async initializeMedia() {
609
730
  try {
610
- // Initialize media manager
611
- await this.mesh.initializeMedia();
612
-
613
- // Populate device lists
614
- await this.updateDeviceLists();
615
-
616
- // Update button states
617
- this.updateMediaButtonStates();
618
-
619
- console.log('Media initialized successfully');
731
+ this.addCryptoTestResult(`🔄 Sending encrypted group message to ${groupId}...`, 'info');
732
+ await this.mesh.sendEncryptedBroadcast(message, groupId);
733
+ this.addCryptoTestResult('✅ Encrypted group message sent', 'success');
734
+ groupMessageInput.value = '';
620
735
  } catch (error) {
621
- console.error('Failed to initialize media:', error);
622
- this.addMessage('System', `Failed to initialize media: ${error.message}`, 'error');
736
+ this.addCryptoTestResult(`❌ Failed to send group message: ${error.message}`, 'error');
623
737
  }
738
+ });
624
739
  }
625
740
 
626
- async updateDeviceLists() {
741
+ // Advanced Controls Event Handlers
742
+ if (exportKeyBtn) {
743
+ exportKeyBtn.addEventListener('click', () => {
627
744
  try {
628
- const devices = await this.mesh.enumerateMediaDevices();
629
-
630
- // Update camera list
631
- const cameraSelect = document.getElementById('camera-select');
632
- if (cameraSelect) {
633
- cameraSelect.innerHTML = '<option value="">Select camera...</option>';
634
- devices.cameras.forEach(device => {
635
- const option = document.createElement('option');
636
- option.value = device.deviceId;
637
- option.textContent = device.label || `Camera ${device.deviceId.substring(0, 8)}...`;
638
- cameraSelect.appendChild(option);
639
- });
640
- cameraSelect.disabled = devices.cameras.length === 0;
641
- }
642
-
643
- // Update microphone list
644
- const micSelect = document.getElementById('microphone-select');
645
- if (micSelect) {
646
- micSelect.innerHTML = '<option value="">Select microphone...</option>';
647
- devices.microphones.forEach(device => {
648
- const option = document.createElement('option');
649
- option.value = device.deviceId;
650
- option.textContent = device.label || `Microphone ${device.deviceId.substring(0, 8)}...`;
651
- micSelect.appendChild(option);
652
- });
653
- micSelect.disabled = devices.microphones.length === 0;
654
- }
655
-
745
+ const keyData = this.mesh.exportPublicKey();
746
+ if (keyData) {
747
+ const exportText = JSON.stringify(keyData, null, 2);
748
+ navigator.clipboard.writeText(exportText).then(() => {
749
+ this.addCryptoTestResult('✅ Public key copied to clipboard', 'success');
750
+ }).catch(() => {
751
+ // Fallback - show in alert
752
+ alert('Public Key:\n\n' + exportText);
753
+ this.addCryptoTestResult('✅ Public key exported (check dialog)', 'success');
754
+ });
755
+ } else {
756
+ this.addCryptoTestResult('❌ No public key available to export', 'error');
757
+ }
656
758
  } catch (error) {
657
- console.error('Failed to update device lists:', error);
759
+ this.addCryptoTestResult(`❌ Failed to export key: ${error.message}`, 'error');
658
760
  }
761
+ });
659
762
  }
660
763
 
661
- updateMediaButtonStates() {
662
- const videoEnabled = document.getElementById('enable-video')?.checked || false;
663
- const audioEnabled = document.getElementById('enable-audio')?.checked || false;
664
- const mediaState = this.mesh.getMediaState();
665
-
666
- // Enable start button if at least one media type is selected
667
- const startBtn = document.getElementById('start-media-btn');
668
- if (startBtn) {
669
- startBtn.disabled = !(videoEnabled || audioEnabled) || mediaState.hasLocalStream;
670
- }
671
-
672
- // Enable stop button if media is active
673
- const stopBtn = document.getElementById('stop-media-btn');
674
- if (stopBtn) {
675
- stopBtn.disabled = !mediaState.hasLocalStream;
676
- }
677
-
678
- // Enable toggle buttons if media is active
679
- const toggleVideoBtn = document.getElementById('toggle-video-btn');
680
- const toggleAudioBtn = document.getElementById('toggle-audio-btn');
681
-
682
- if (toggleVideoBtn) {
683
- toggleVideoBtn.disabled = !mediaState.hasLocalStream;
684
- toggleVideoBtn.textContent = mediaState.videoEnabled ? 'Turn Off Video' : 'Turn On Video';
764
+ if (importPeerKeyBtn && importForm) {
765
+ importPeerKeyBtn.addEventListener('click', () => {
766
+ importForm.style.display = importForm.style.display === 'none' ? 'block' : 'none';
767
+ });
768
+ }
769
+
770
+ if (importConfirmBtn && importPeerIdInput && importPublicKeyInput && importForm) {
771
+ importConfirmBtn.addEventListener('click', () => {
772
+ const peerId = importPeerIdInput.value.trim();
773
+ const publicKey = importPublicKeyInput.value.trim();
774
+
775
+ if (!peerId || peerId.length !== 40) {
776
+ this.addCryptoTestResult('❌ Valid 40-character peer ID is required', 'error');
777
+ return;
685
778
  }
686
-
687
- if (toggleAudioBtn) {
688
- toggleAudioBtn.disabled = !mediaState.hasLocalStream;
689
- toggleAudioBtn.textContent = mediaState.audioEnabled ? 'Turn Off Audio' : 'Turn On Audio';
779
+
780
+ if (!publicKey) {
781
+ this.addCryptoTestResult('❌ Public key is required', 'error');
782
+ return;
690
783
  }
691
- }
692
784
 
693
- async startMedia() {
694
785
  try {
695
- const videoEnabled = document.getElementById('enable-video')?.checked || false;
696
- const audioEnabled = document.getElementById('enable-audio')?.checked || false;
697
-
698
- // Initialize audio context for better audio support
699
- if (audioEnabled && (window.AudioContext || window.webkitAudioContext)) {
700
- const AudioContext = window.AudioContext || window.webkitAudioContext;
701
- try {
702
- const audioContext = new AudioContext();
703
- if (audioContext.state === 'suspended') {
704
- await audioContext.resume();
705
- console.log('Audio context resumed for local media');
706
- }
707
- console.log('Audio context state:', audioContext.state);
708
- } catch (e) {
709
- console.log('Could not initialize audio context:', e);
710
- }
786
+ // Try to parse as JSON first (for full keypair with pub/epub)
787
+ let keyData;
788
+ try {
789
+ keyData = JSON.parse(publicKey);
790
+ // Validate that it has the expected structure
791
+ if (!keyData.pub && !keyData.epub && !keyData.publicKey) {
792
+ throw new Error('Invalid key format');
711
793
  }
712
-
713
- const deviceIds = {};
714
- const cameraSelect = document.getElementById('camera-select');
715
- const micSelect = document.getElementById('microphone-select');
716
-
717
- if (cameraSelect?.value) {
718
- deviceIds.camera = cameraSelect.value;
794
+ } catch (jsonError) {
795
+ // If JSON parsing fails, treat as plain string (legacy format)
796
+ keyData = publicKey;
797
+ }
798
+
799
+ const success = this.mesh.addPeerPublicKey(peerId, keyData);
800
+ if (success) {
801
+ const keyType = typeof keyData === 'object'
802
+ ? (keyData.pub && keyData.epub ? 'complete keypair' : 'partial key')
803
+ : 'legacy key';
804
+ this.addCryptoTestResult(`✅ Public key imported for ${peerId.substring(0, 8)}... (${keyType})`, 'success');
805
+ if (typeof keyData === 'string' || !keyData.epub) {
806
+ this.addCryptoTestResult('⚠️ Warning: Only signing key imported. Encryption may not work.', 'warning');
719
807
  }
720
-
721
- if (micSelect?.value) {
722
- deviceIds.microphone = micSelect.value;
723
- }
724
-
725
- await this.mesh.startMedia({
726
- video: videoEnabled,
727
- audio: audioEnabled,
728
- deviceIds
729
- });
730
-
731
- this.addMessage('System', 'Media started successfully');
732
- this.updateMediaButtonStates();
733
-
808
+ this.updateCryptoStatus();
809
+ importPeerIdInput.value = '';
810
+ importPublicKeyInput.value = '';
811
+ importForm.style.display = 'none';
812
+ } else {
813
+ this.addCryptoTestResult('❌ Failed to import public key', 'error');
814
+ }
734
815
  } catch (error) {
735
- console.error('Failed to start media:', error);
736
- this.addMessage('System', `Failed to start media: ${error.message}`, 'error');
816
+ this.addCryptoTestResult(`❌ Failed to import key: ${error.message}`, 'error');
737
817
  }
818
+ });
738
819
  }
739
820
 
740
- async stopMedia() {
741
- try {
742
- await this.mesh.stopMedia();
743
- this.addMessage('System', 'Media stopped');
744
- this.updateMediaButtonStates();
745
- this.clearLocalVideo();
746
-
747
- } catch (error) {
748
- console.error('Failed to stop media:', error);
749
- this.addMessage('System', `Failed to stop media: ${error.message}`, 'error');
750
- }
821
+ if (importCancelBtn && importForm) {
822
+ importCancelBtn.addEventListener('click', () => {
823
+ importForm.style.display = 'none';
824
+ if (importPeerIdInput) importPeerIdInput.value = '';
825
+ if (importPublicKeyInput) importPublicKeyInput.value = '';
826
+ });
751
827
  }
752
828
 
753
- toggleVideo() {
829
+ if (benchmarkBtn) {
830
+ benchmarkBtn.addEventListener('click', async () => {
754
831
  try {
755
- const enabled = this.mesh.toggleVideo();
756
- this.addMessage('System', `Video ${enabled ? 'enabled' : 'disabled'}`);
757
- this.updateMediaButtonStates();
832
+ this.addCryptoTestResult('🔄 Running crypto benchmark...', 'info');
833
+
834
+ const testData = 'This is a test message for benchmarking crypto performance.';
835
+ const iterations = 100;
836
+
837
+ // Test encryption/decryption performance
838
+ const startTime = performance.now();
839
+ for (let i = 0; i < iterations; i++) {
840
+ const encrypted = await this.mesh.encryptMessage(testData);
841
+ await this.mesh.decryptMessage(encrypted);
842
+ }
843
+ const endTime = performance.now();
844
+
845
+ const totalTime = endTime - startTime;
846
+ const avgTime = totalTime / iterations;
847
+
848
+ this.addCryptoTestResult(`✅ Benchmark completed: ${iterations} iterations`, 'success');
849
+ this.addCryptoTestResult(` Total time: ${totalTime.toFixed(2)}ms`, 'info');
850
+ this.addCryptoTestResult(` Average time per cycle: ${avgTime.toFixed(2)}ms`, 'info');
758
851
  } catch (error) {
759
- console.error('Failed to toggle video:', error);
760
- this.addMessage('System', `Failed to toggle video: ${error.message}`, 'error');
852
+ this.addCryptoTestResult(`❌ Benchmark failed: ${error.message}`, 'error');
761
853
  }
854
+ });
762
855
  }
856
+ }
857
+
858
+ setupMediaControls() {
859
+ // Start media button
860
+ document.getElementById('start-media-btn').addEventListener('click', async () => {
861
+ await this.startMedia();
862
+ });
863
+
864
+ // Stop media button
865
+ document.getElementById('stop-media-btn').addEventListener('click', async () => {
866
+ await this.stopMedia();
867
+ });
868
+
869
+ // Toggle video button
870
+ document.getElementById('toggle-video-btn').addEventListener('click', () => {
871
+ this.toggleVideo();
872
+ });
873
+
874
+ // Toggle audio button
875
+ document.getElementById('toggle-audio-btn').addEventListener('click', () => {
876
+ this.toggleAudio();
877
+ });
878
+
879
+ // Audio test button
880
+ document.getElementById('test-audio-btn').addEventListener('click', () => {
881
+ this.testAudio();
882
+ });
883
+
884
+ // Media type checkboxes
885
+ document.getElementById('enable-video').addEventListener('change', () => {
886
+ this.updateMediaButtonStates();
887
+ });
888
+
889
+ document.getElementById('enable-audio').addEventListener('change', () => {
890
+ this.updateMediaButtonStates();
891
+ });
892
+
893
+ // Device selection dropdowns
894
+ document.getElementById('camera-select').addEventListener('change', () => {
895
+ // Auto-restart media if it's currently active
896
+ if (this.mesh.getMediaState().hasLocalStream) {
897
+ this.startMedia();
898
+ }
899
+ });
900
+
901
+ document.getElementById('microphone-select').addEventListener('change', () => {
902
+ // Auto-restart media if it's currently active
903
+ if (this.mesh.getMediaState().hasLocalStream) {
904
+ this.startMedia();
905
+ }
906
+ });
907
+ }
908
+
909
+ setupCollapsibleSections() {
910
+ const sections = [
911
+ 'discovered-peers',
912
+ 'connected-peers',
913
+ 'manual-connection',
914
+ 'settings',
915
+ 'dht',
916
+ 'crypto',
917
+ 'media'
918
+ ];
919
+
920
+ sections.forEach(sectionId => {
921
+ const toggle = document.getElementById(`${sectionId}-toggle`);
922
+ const content = document.getElementById(`${sectionId}-content`);
923
+
924
+ if (toggle && content) {
925
+ toggle.addEventListener('click', () => {
926
+ this.toggleSection(sectionId);
927
+ });
928
+ }
929
+ });
930
+ }
763
931
 
764
- toggleAudio() {
765
- try {
766
- const enabled = this.mesh.toggleAudio();
767
- this.addMessage('System', `Audio ${enabled ? 'enabled' : 'disabled'}`);
768
- this.updateMediaButtonStates();
769
- } catch (error) {
770
- console.error('Failed to toggle audio:', error);
771
- this.addMessage('System', `Failed to toggle audio: ${error.message}`, 'error');
772
- }
932
+ toggleSection(sectionId) {
933
+ const toggle = document.getElementById(`${sectionId}-toggle`);
934
+ const content = document.getElementById(`${sectionId}-content`);
935
+
936
+ if (!toggle || !content) {
937
+ console.warn(`Could not find elements for section: ${sectionId}`);
938
+ return;
773
939
  }
774
940
 
775
- async testAudio() {
776
- try {
777
- console.log('🔊 Starting audio test...');
778
- this.addMessage('System', '🔊 Testing audio system...', 'info');
779
-
780
- // First, run diagnostics to understand current state
781
- this.logPeerDiagnostics();
782
-
783
- // Test 0: Verify we have actual peer connections (not just self)
784
- const allPeers = this.mesh.getPeers();
785
- const connectedPeers = allPeers.filter(peer => peer.status === 'connected');
786
- const peersWithMedia = allPeers.filter(peer => {
787
- const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
788
- return peerConnection && (peerConnection.remoteStream || peerConnection.connection?.connectionState === 'connected');
789
- });
790
-
791
- console.log('🔊 All peers:', allPeers.length);
792
- console.log('🔊 Connected peers (data channel):', connectedPeers.length);
793
- console.log('🔊 Peers with media/WebRTC:', peersWithMedia.length);
794
-
795
- // Log detailed peer status
796
- allPeers.forEach(peer => {
797
- const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
798
- console.log(`🔊 Peer ${peer.peerId.substring(0, 8)}:`, {
799
- status: peer.status,
800
- webrtcState: peerConnection?.connection?.connectionState,
801
- dataChannelState: peerConnection?.dataChannel?.readyState,
802
- hasRemoteStream: !!peerConnection?.remoteStream,
803
- hasLocalStream: !!peerConnection?.localStream
804
- });
805
- });
806
-
807
- this.addMessage('System', `🔊 Found ${allPeers.length} total peers (${connectedPeers.length} with data channel, ${peersWithMedia.length} with media)`, 'info');
808
-
809
- if (peersWithMedia.length === 0) {
810
- this.addMessage('System', '❌ No peers with active media! You need to open this in TWO different browser tabs/windows and connect them.', 'error');
811
- console.log('❌ NO PEERS WITH MEDIA: Open this URL in two different browser tabs and ensure they connect to each other');
812
- return;
813
- }
814
-
815
- // Test each peer connection individually
816
- peersWithMedia.forEach((peer, index) => {
817
- const connection = this.mesh.connectionManager.peers.get(peer.peerId);
818
- if (connection) {
819
- console.log(`🔊 Peer ${index + 1} (${peer.peerId.substring(0, 8)}...):`);
820
-
821
- const localStream = connection.getLocalStream();
822
- const remoteStream = connection.getRemoteStream();
823
-
824
- // Check local stream
825
- if (localStream) {
826
- const localAudioTracks = localStream.getAudioTracks();
827
- console.log(` - Local audio tracks: ${localAudioTracks.length}`);
828
- this.addMessage('System', ` Peer ${index + 1} - Local audio: ${localAudioTracks.length} tracks`, 'info');
829
- localAudioTracks.forEach((track, i) => {
830
- console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}...`);
831
- });
832
- } else {
833
- console.log(' - No local stream');
834
- this.addMessage('System', ` Peer ${index + 1} - No local stream`, 'warning');
835
- }
836
-
837
- // Check remote stream
838
- if (remoteStream) {
839
- const remoteAudioTracks = remoteStream.getAudioTracks();
840
- console.log(` - Remote audio tracks: ${remoteAudioTracks.length}`);
841
- this.addMessage('System', ` Peer ${index + 1} - Remote audio: ${remoteAudioTracks.length} tracks`, remoteAudioTracks.length > 0 ? 'success' : 'warning');
842
-
843
- remoteAudioTracks.forEach((track, i) => {
844
- console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}..., readyState=${track.readyState}`);
845
- });
846
-
847
- // CRITICAL: Check if remote stream ID matches local stream ID (loopback detection)
848
- if (localStream && remoteStream.id === localStream.id) {
849
- console.error(`❌ LOOPBACK DETECTED: Remote stream ID matches local stream ID!`);
850
- this.addMessage('System', `❌ Peer ${index + 1} - LOOPBACK: Getting own audio back!`, 'error');
851
- } else {
852
- console.log(`✅ Stream IDs different: local=${localStream?.id.substring(0, 8) || 'none'}, remote=${remoteStream.id.substring(0, 8)}`);
853
- this.addMessage('System', `✅ Peer ${index + 1} - Stream IDs are different (good!)`, 'success');
854
- }
855
-
856
- // Check video elements playing this stream
857
- const videoElements = document.querySelectorAll('video');
858
- let foundVideoElement = false;
859
- videoElements.forEach(video => {
860
- if (video.srcObject === remoteStream) {
861
- foundVideoElement = true;
862
- console.log(` - Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}, readyState=${video.readyState}`);
863
- this.addMessage('System', ` Peer ${index + 1} - Video element: volume=${video.volume}, muted=${video.muted}`, video.muted ? 'warning' : 'success');
864
- }
865
- });
866
-
867
- if (!foundVideoElement) {
868
- console.log(` - ❌ No video element found for this remote stream`);
869
- this.addMessage('System', ` Peer ${index + 1} - ❌ No video element displaying this stream`, 'error');
870
- }
871
- } else {
872
- console.log(' - ❌ No remote stream');
873
- this.addMessage('System', ` Peer ${index + 1} - ❌ No remote stream received`, 'error');
874
- }
875
- } else {
876
- console.log(`❌ No connection object found for peer ${peer.peerId}`);
877
- this.addMessage('System', `❌ No connection for peer ${index + 1}`, 'error');
878
- }
879
- });
880
-
881
- // Test 1: Audio Context
882
- if (window.AudioContext || window.webkitAudioContext) {
883
- const AudioContext = window.AudioContext || window.webkitAudioContext;
884
- const audioContext = new AudioContext();
885
- console.log('Audio context state:', audioContext.state);
886
-
887
- if (audioContext.state === 'suspended') {
888
- await audioContext.resume();
889
- console.log('Audio context resumed');
890
- }
891
-
892
- // Generate a test tone
893
- const oscillator = audioContext.createOscillator();
894
- const gainNode = audioContext.createGain();
895
-
896
- oscillator.connect(gainNode);
897
- gainNode.connect(audioContext.destination);
898
-
899
- oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4 note
900
- gainNode.gain.setValueAtTime(0.1, audioContext.currentTime); // Low volume
901
-
902
- oscillator.start();
903
- oscillator.stop(audioContext.currentTime + 0.5); // Play for 0.5 seconds
904
-
905
- this.addMessage('System', '🔊 Audio test tone played (440Hz for 0.5s)', 'success');
906
- } else {
907
- this.addMessage('System', '❌ Audio context not supported', 'error');
908
- }
909
-
910
- // Test 2: Check current media streams
911
- const peers = this.mesh.getPeers();
912
- console.log('Current peers:', peers.length);
913
-
914
- peers.forEach(peer => {
915
- const connection = this.mesh.connectionManager.peers.get(peer.peerId);
916
- if (connection) {
917
- const localStream = connection.getLocalStream();
918
- const remoteStream = connection.getRemoteStream();
919
-
920
- console.log(`Peer ${peer.peerId.substring(0, 8)}:`);
921
- if (localStream) {
922
- const audioTracks = localStream.getAudioTracks();
923
- console.log(`- Local audio tracks: ${audioTracks.length}`);
924
- audioTracks.forEach((track, i) => {
925
- console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
926
- });
927
- }
928
-
929
- if (remoteStream) {
930
- const audioTracks = remoteStream.getAudioTracks();
931
- console.log(`- Remote audio tracks: ${audioTracks.length}`);
932
- audioTracks.forEach((track, i) => {
933
- console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
934
- });
935
-
936
- // Check if there are video elements for this stream
937
- const videoElements = document.querySelectorAll('video');
938
- videoElements.forEach(video => {
939
- if (video.srcObject === remoteStream) {
940
- console.log(`- Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}`);
941
- }
942
- });
943
- }
944
- }
945
- });
946
-
947
- // Test 3: Check microphone access
948
- try {
949
- const testStream = await navigator.mediaDevices.getUserMedia({ audio: true });
950
- console.log('✅ Microphone access working');
951
- this.addMessage('System', '✅ Microphone access: OK', 'success');
952
- testStream.getTracks().forEach(track => track.stop());
953
- } catch (error) {
954
- console.log('❌ Microphone access failed:', error);
955
- this.addMessage('System', `❌ Microphone access failed: ${error.message}`, 'error');
956
- }
957
-
958
- } catch (error) {
959
- console.error('Audio test failed:', error);
960
- this.addMessage('System', `❌ Audio test failed: ${error.message}`, 'error');
961
- }
941
+ const section = toggle.closest(`.${sectionId}`);
942
+
943
+ if (!section) {
944
+ console.warn(`Could not find section container for: ${sectionId}`, {
945
+ toggle,
946
+ toggleParent: toggle.parentElement,
947
+ toggleParentParent: toggle.parentElement?.parentElement,
948
+ classList: toggle.parentElement?.parentElement?.classList
949
+ });
950
+ return;
962
951
  }
963
952
 
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;
953
+ const isExpanded = toggle.getAttribute('aria-expanded') === 'true';
954
+
955
+ toggle.setAttribute('aria-expanded', !isExpanded);
956
+
957
+ // Add null check before calling setAttribute
958
+ if (section) {
959
+ section.setAttribute('aria-expanded', !isExpanded);
1001
960
  }
1002
961
 
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
- }
962
+ if (isExpanded) {
963
+ content.style.display = 'none';
964
+ toggle.textContent = toggle.textContent.replace('▼', '▶');
965
+ } else {
966
+ content.style.display = 'block';
967
+ toggle.textContent = toggle.textContent.replace('▶', '▼');
968
+ }
969
+ }
970
+
971
+ // Media-related methods
972
+ async initializeMedia() {
973
+ try {
974
+ // Initialize media manager
975
+ await this.mesh.initializeMedia();
976
+
977
+ // Populate device lists
978
+ await this.updateDeviceLists();
979
+
980
+ // Update button states
981
+ this.updateMediaButtonStates();
982
+
983
+ console.log('Media initialized successfully');
984
+ } catch (error) {
985
+ console.error('Failed to initialize media:', error);
986
+ this.addMessage('System', `Failed to initialize media: ${error.message}`, 'error');
987
+ }
988
+ }
989
+
990
+ async updateDeviceLists() {
991
+ try {
992
+ const devices = await this.mesh.enumerateMediaDevices();
993
+
994
+ // Update camera list
995
+ const cameraSelect = document.getElementById('camera-select');
996
+ if (cameraSelect) {
997
+ cameraSelect.innerHTML = '<option value="">Select camera...</option>';
998
+ devices.cameras.forEach(device => {
999
+ const option = document.createElement('option');
1000
+ option.value = device.deviceId;
1001
+ option.textContent = device.label || `Camera ${device.deviceId.substring(0, 8)}...`;
1002
+ cameraSelect.appendChild(option);
1003
+ });
1004
+ cameraSelect.disabled = devices.cameras.length === 0;
1005
+ }
1006
+
1007
+ // Update microphone list
1008
+ const micSelect = document.getElementById('microphone-select');
1009
+ if (micSelect) {
1010
+ micSelect.innerHTML = '<option value="">Select microphone...</option>';
1011
+ devices.microphones.forEach(device => {
1012
+ const option = document.createElement('option');
1013
+ option.value = device.deviceId;
1014
+ option.textContent = device.label || `Microphone ${device.deviceId.substring(0, 8)}...`;
1015
+ micSelect.appendChild(option);
1016
+ });
1017
+ micSelect.disabled = devices.microphones.length === 0;
1018
+ }
1019
+ } catch (error) {
1020
+ console.error('Failed to update device lists:', error);
1021
+ }
1022
+ }
1023
+
1024
+ updateMediaButtonStates() {
1025
+ const videoEnabled = document.getElementById('enable-video')?.checked || false;
1026
+ const audioEnabled = document.getElementById('enable-audio')?.checked || false;
1027
+ const mediaState = this.mesh.getMediaState();
1028
+
1029
+ // Enable start button if at least one media type is selected
1030
+ const startBtn = document.getElementById('start-media-btn');
1031
+ if (startBtn) {
1032
+ startBtn.disabled = !(videoEnabled || audioEnabled) || mediaState.hasLocalStream;
1012
1033
  }
1013
1034
 
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
1035
+ // Enable stop button if media is active
1036
+ const stopBtn = document.getElementById('stop-media-btn');
1037
+ if (stopBtn) {
1038
+ stopBtn.disabled = !mediaState.hasLocalStream;
1039
+ }
1040
+
1041
+ // Enable toggle buttons if media is active
1042
+ const toggleVideoBtn = document.getElementById('toggle-video-btn');
1043
+ const toggleAudioBtn = document.getElementById('toggle-audio-btn');
1044
+
1045
+ if (toggleVideoBtn) {
1046
+ toggleVideoBtn.disabled = !mediaState.hasLocalStream;
1047
+ toggleVideoBtn.textContent = mediaState.videoEnabled ? 'Turn Off Video' : 'Turn On Video';
1048
+ }
1049
+
1050
+ if (toggleAudioBtn) {
1051
+ toggleAudioBtn.disabled = !mediaState.hasLocalStream;
1052
+ toggleAudioBtn.textContent = mediaState.audioEnabled ? 'Turn Off Audio' : 'Turn On Audio';
1053
+ }
1054
+ }
1055
+
1056
+ async startMedia() {
1057
+ try {
1058
+ const videoEnabled = document.getElementById('enable-video')?.checked || false;
1059
+ const audioEnabled = document.getElementById('enable-audio')?.checked || false;
1060
+
1061
+ // Initialize audio context for better audio support
1062
+ if (audioEnabled && (window.AudioContext || window.webkitAudioContext)) {
1063
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
1064
+ try {
1065
+ const audioContext = new AudioContext();
1066
+ if (audioContext.state === 'suspended') {
1067
+ await audioContext.resume();
1068
+ console.log('Audio context resumed for local media');
1069
+ }
1070
+ console.log('Audio context state:', audioContext.state);
1071
+ } catch (e) {
1072
+ console.log('Could not initialize audio context:', e);
1023
1073
  }
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`);
1074
+ }
1075
+
1076
+ const deviceIds = {};
1077
+ const cameraSelect = document.getElementById('camera-select');
1078
+ const micSelect = document.getElementById('microphone-select');
1079
+
1080
+ if (cameraSelect?.value) {
1081
+ deviceIds.camera = cameraSelect.value;
1082
+ }
1083
+
1084
+ if (micSelect?.value) {
1085
+ deviceIds.microphone = micSelect.value;
1086
+ }
1087
+
1088
+ await this.mesh.startMedia({
1089
+ video: videoEnabled,
1090
+ audio: audioEnabled,
1091
+ deviceIds
1092
+ });
1093
+
1094
+ this.addMessage('System', 'Media started successfully');
1095
+ this.updateMediaButtonStates();
1096
+ } catch (error) {
1097
+ console.error('Failed to start media:', error);
1098
+ this.addMessage('System', `Failed to start media: ${error.message}`, 'error');
1099
+ }
1100
+ }
1101
+
1102
+ async stopMedia() {
1103
+ try {
1104
+ await this.mesh.stopMedia();
1105
+ this.addMessage('System', 'Media stopped');
1106
+ this.updateMediaButtonStates();
1107
+ this.clearLocalVideo();
1108
+ } catch (error) {
1109
+ console.error('Failed to stop media:', error);
1110
+ this.addMessage('System', `Failed to stop media: ${error.message}`, 'error');
1111
+ }
1112
+ }
1113
+
1114
+ toggleVideo() {
1115
+ try {
1116
+ const enabled = this.mesh.toggleVideo();
1117
+ this.addMessage('System', `Video ${enabled ? 'enabled' : 'disabled'}`);
1118
+ this.updateMediaButtonStates();
1119
+ } catch (error) {
1120
+ console.error('Failed to toggle video:', error);
1121
+ this.addMessage('System', `Failed to toggle video: ${error.message}`, 'error');
1122
+ }
1123
+ }
1124
+
1125
+ toggleAudio() {
1126
+ try {
1127
+ const enabled = this.mesh.toggleAudio();
1128
+ this.addMessage('System', `Audio ${enabled ? 'enabled' : 'disabled'}`);
1129
+ this.updateMediaButtonStates();
1130
+ } catch (error) {
1131
+ console.error('Failed to toggle audio:', error);
1132
+ this.addMessage('System', `Failed to toggle audio: ${error.message}`, 'error');
1133
+ }
1134
+ }
1135
+
1136
+ async testAudio() {
1137
+ try {
1138
+ console.log('🔊 Starting audio test...');
1139
+ this.addMessage('System', '🔊 Testing audio system...', 'info');
1140
+
1141
+ // First, run diagnostics to understand current state
1142
+ this.logPeerDiagnostics();
1143
+
1144
+ // Test 0: Verify we have actual peer connections (not just self)
1145
+ const allPeers = this.mesh.getPeers();
1146
+ const connectedPeers = allPeers.filter(peer => peer.status === 'connected');
1147
+ const peersWithMedia = allPeers.filter(peer => {
1148
+ const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
1149
+ return peerConnection && (peerConnection.remoteStream || peerConnection.connection?.connectionState === 'connected');
1150
+ });
1151
+
1152
+ console.log('🔊 All peers:', allPeers.length);
1153
+ console.log('🔊 Connected peers (data channel):', connectedPeers.length);
1154
+ console.log('🔊 Peers with media/WebRTC:', peersWithMedia.length);
1155
+
1156
+ // Log detailed peer status
1157
+ allPeers.forEach(peer => {
1158
+ const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
1159
+ console.log(`🔊 Peer ${peer.peerId.substring(0, 8)}:`, {
1160
+ status: peer.status,
1161
+ webrtcState: peerConnection?.connection?.connectionState,
1162
+ dataChannelState: peerConnection?.dataChannel?.readyState,
1163
+ hasRemoteStream: !!peerConnection?.remoteStream,
1164
+ hasLocalStream: !!peerConnection?.localStream
1165
+ });
1166
+ });
1167
+
1168
+ this.addMessage('System', `🔊 Found ${allPeers.length} total peers (${connectedPeers.length} with data channel, ${peersWithMedia.length} with media)`, 'info');
1169
+
1170
+ if (peersWithMedia.length === 0) {
1171
+ this.addMessage('System', '❌ No peers with active media! You need to open this in TWO different browser tabs/windows and connect them.', 'error');
1172
+ console.log('❌ NO PEERS WITH MEDIA: Open this URL in two different browser tabs and ensure they connect to each other');
1173
+ return;
1174
+ }
1175
+
1176
+ // Test each peer connection individually
1177
+ peersWithMedia.forEach((peer, index) => {
1178
+ const connection = this.mesh.connectionManager.peers.get(peer.peerId);
1179
+ if (connection) {
1180
+ console.log(`🔊 Peer ${index + 1} (${peer.peerId.substring(0, 8)}...):`);
1181
+
1182
+ const localStream = connection.getLocalStream();
1183
+ const remoteStream = connection.getRemoteStream();
1184
+
1185
+ // Check local stream
1186
+ if (localStream) {
1187
+ const localAudioTracks = localStream.getAudioTracks();
1188
+ console.log(` - Local audio tracks: ${localAudioTracks.length}`);
1189
+ this.addMessage('System', ` Peer ${index + 1} - Local audio: ${localAudioTracks.length} tracks`, 'info');
1190
+ localAudioTracks.forEach((track, i) => {
1191
+ console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}...`);
1044
1192
  });
1045
-
1046
- track.addEventListener('mute', () => {
1047
- console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} MUTED`);
1193
+ } else {
1194
+ console.log(' - No local stream');
1195
+ this.addMessage('System', ` Peer ${index + 1} - No local stream`, 'warning');
1196
+ }
1197
+
1198
+ // Check remote stream
1199
+ if (remoteStream) {
1200
+ const remoteAudioTracks = remoteStream.getAudioTracks();
1201
+ console.log(` - Remote audio tracks: ${remoteAudioTracks.length}`);
1202
+ this.addMessage('System', ` Peer ${index + 1} - Remote audio: ${remoteAudioTracks.length} tracks`, remoteAudioTracks.length > 0 ? 'success' : 'warning');
1203
+
1204
+ remoteAudioTracks.forEach((track, i) => {
1205
+ console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}..., readyState=${track.readyState}`);
1048
1206
  });
1049
-
1050
- track.addEventListener('unmute', () => {
1051
- console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} UNMUTED`);
1207
+
1208
+ // CRITICAL: Check if remote stream ID matches local stream ID (loopback detection)
1209
+ if (localStream && remoteStream.id === localStream.id) {
1210
+ console.error('❌ LOOPBACK DETECTED: Remote stream ID matches local stream ID!');
1211
+ this.addMessage('System', `❌ Peer ${index + 1} - LOOPBACK: Getting own audio back!`, 'error');
1212
+ } else {
1213
+ console.log(`✅ Stream IDs different: local=${localStream?.id.substring(0, 8) || 'none'}, remote=${remoteStream.id.substring(0, 8)}`);
1214
+ this.addMessage('System', `✅ Peer ${index + 1} - Stream IDs are different (good!)`, 'success');
1215
+ }
1216
+
1217
+ // Check video elements playing this stream
1218
+ const videoElements = document.querySelectorAll('video');
1219
+ let foundVideoElement = false;
1220
+ videoElements.forEach(video => {
1221
+ if (video.srcObject === remoteStream) {
1222
+ foundVideoElement = true;
1223
+ console.log(` - Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}, readyState=${video.readyState}`);
1224
+ this.addMessage('System', ` Peer ${index + 1} - Video element: volume=${video.volume}, muted=${video.muted}`, video.muted ? 'warning' : 'success');
1225
+ }
1052
1226
  });
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`);
1227
+
1228
+ if (!foundVideoElement) {
1229
+ console.log(' - ❌ No video element found for this remote stream');
1230
+ this.addMessage('System', ` Peer ${index + 1} - ❌ No video element displaying this stream`, 'error');
1231
+ }
1232
+ } else {
1233
+ console.log(' - ❌ No remote stream');
1234
+ this.addMessage('System', ` Peer ${index + 1} - ❌ No remote stream received`, 'error');
1235
+ }
1071
1236
  } else {
1072
- console.log(`❌ NO AUDIO TRACKS from peer ${audioSummary.peerIdShort} - video only`);
1237
+ console.log(`❌ No connection object found for peer ${peer.peerId}`);
1238
+ this.addMessage('System', `❌ No connection for peer ${index + 1}`, 'error');
1073
1239
  }
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.');
1240
+ });
1241
+
1242
+ // Test 1: Audio Context
1243
+ if (window.AudioContext || window.webkitAudioContext) {
1244
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
1245
+ const audioContext = new AudioContext();
1246
+ console.log('Audio context state:', audioContext.state);
1247
+
1248
+ if (audioContext.state === 'suspended') {
1249
+ await audioContext.resume();
1250
+ console.log('Audio context resumed');
1086
1251
  }
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');
1252
+
1253
+ // Generate a test tone
1254
+ const oscillator = audioContext.createOscillator();
1255
+ const gainNode = audioContext.createGain();
1256
+
1257
+ oscillator.connect(gainNode);
1258
+ gainNode.connect(audioContext.destination);
1259
+
1260
+ oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4 note
1261
+ gainNode.gain.setValueAtTime(0.1, audioContext.currentTime); // Low volume
1262
+
1263
+ oscillator.start();
1264
+ oscillator.stop(audioContext.currentTime + 0.5); // Play for 0.5 seconds
1265
+
1266
+ this.addMessage('System', '🔊 Audio test tone played (440Hz for 0.5s)', 'success');
1267
+ } else {
1268
+ this.addMessage('System', '❌ Audio context not supported', 'error');
1269
+ }
1270
+
1271
+ // Test 2: Check current media streams
1272
+ const peers = this.mesh.getPeers();
1273
+ console.log('Current peers:', peers.length);
1274
+
1275
+ peers.forEach(peer => {
1276
+ const connection = this.mesh.connectionManager.peers.get(peer.peerId);
1277
+ if (connection) {
1278
+ const localStream = connection.getLocalStream();
1279
+ const remoteStream = connection.getRemoteStream();
1280
+
1281
+ console.log(`Peer ${peer.peerId.substring(0, 8)}:`);
1282
+ if (localStream) {
1283
+ const audioTracks = localStream.getAudioTracks();
1284
+ console.log(`- Local audio tracks: ${audioTracks.length}`);
1285
+ audioTracks.forEach((track, i) => {
1286
+ console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
1162
1287
  });
1163
-
1164
- video.addEventListener('pause', () => {
1165
- console.log('Video element paused');
1288
+ }
1289
+
1290
+ if (remoteStream) {
1291
+ const audioTracks = remoteStream.getAudioTracks();
1292
+ console.log(`- Remote audio tracks: ${audioTracks.length}`);
1293
+ audioTracks.forEach((track, i) => {
1294
+ console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
1166
1295
  });
1167
-
1168
- video.addEventListener('volumechange', () => {
1169
- console.log('Volume changed:', video.volume, 'Muted:', video.muted);
1296
+
1297
+ // Check if there are video elements for this stream
1298
+ const videoElements = document.querySelectorAll('video');
1299
+ videoElements.forEach(video => {
1300
+ if (video.srcObject === remoteStream) {
1301
+ console.log(`- Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}`);
1302
+ }
1170
1303
  });
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: stream,
1190
- streamId: stream.id,
1191
- streamActive: stream.active,
1192
- videoElement: video,
1193
- videoMuted: video.muted,
1194
- videoVolume: video.volume,
1195
- isOwnStream: 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);
1304
+ }
1228
1305
  }
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 });
1306
+ });
1307
+
1308
+ // Test 3: Check microphone access
1309
+ try {
1310
+ const testStream = await navigator.mediaDevices.getUserMedia({ audio: true });
1311
+ console.log('✅ Microphone access working');
1312
+ this.addMessage('System', '✅ Microphone access: OK', 'success');
1313
+ testStream.getTracks().forEach(track => track.stop());
1314
+ } catch (error) {
1315
+ console.log('❌ Microphone access failed:', error);
1316
+ this.addMessage('System', `❌ Microphone access failed: ${error.message}`, 'error');
1317
+ }
1318
+ } catch (error) {
1319
+ console.error('Audio test failed:', error);
1320
+ this.addMessage('System', `❌ Audio test failed: ${error.message}`, 'error');
1321
+ }
1322
+ }
1323
+
1324
+ handleLocalStreamStarted(data) {
1325
+ this.updateMediaButtonStates();
1326
+
1327
+ // Display local video if video is enabled
1328
+ if (data.video) {
1329
+ this.displayLocalVideo(data.stream);
1330
+ }
1331
+
1332
+ const mediaTypes = [];
1333
+ if (data.video) mediaTypes.push('video');
1334
+ if (data.audio) mediaTypes.push('audio');
1335
+
1336
+ this.addMessage('System', `Local ${mediaTypes.join(' and ')} started`);
1337
+ }
1338
+
1339
+ handleLocalStreamStopped() {
1340
+ this.updateMediaButtonStates();
1341
+ this.clearLocalVideo();
1342
+ this.addMessage('System', 'Local media stopped');
1343
+ }
1344
+
1345
+ displayLocalVideo(stream) {
1346
+ const localVideoContainer = document.getElementById('local-video-container');
1347
+ if (!localVideoContainer) return;
1348
+
1349
+ let video = localVideoContainer.querySelector('video');
1350
+ if (!video) {
1351
+ video = document.createElement('video');
1352
+ video.autoplay = true;
1353
+ video.muted = true;
1354
+ video.playsInline = true;
1355
+ video.style.width = '100%';
1356
+ video.style.borderRadius = '8px';
1357
+ localVideoContainer.appendChild(video);
1358
+ }
1359
+
1360
+ video.srcObject = stream;
1361
+ }
1362
+
1363
+ clearLocalVideo() {
1364
+ const localVideoContainer = document.getElementById('local-video-container');
1365
+ if (localVideoContainer) {
1366
+ const video = localVideoContainer.querySelector('video');
1367
+ if (video) {
1368
+ video.srcObject = null;
1369
+ video.remove();
1370
+ }
1371
+ }
1372
+ }
1373
+
1374
+ handleRemoteStream(data) {
1375
+ console.log('🎵 Handling remote stream:', data);
1376
+ const { peerId, stream } = data;
1377
+
1378
+ // CRITICAL: Prevent audio loopback - check if this is our own stream
1379
+ if (peerId === this.mesh.peerId) {
1380
+ console.warn('🚨 LOOPBACK DETECTED: Received our own stream as remote! This should not happen.');
1381
+ console.warn('Stream ID:', stream.id);
1382
+ // Still display it but it will be muted by displayRemoteVideo
1383
+ }
1384
+
1385
+ // Detailed audio analysis
1386
+ const audioTracks = stream.getAudioTracks();
1387
+ const videoTracks = stream.getVideoTracks();
1388
+
1389
+ console.log(`Stream from ${peerId.substring(0, 8)}: ${audioTracks.length} audio, ${videoTracks.length} video tracks`);
1390
+
1391
+ audioTracks.forEach((track, i) => {
1392
+ console.log(`🎵 Audio track ${i}:`, {
1393
+ id: track.id,
1394
+ kind: track.kind,
1395
+ enabled: track.enabled,
1396
+ readyState: track.readyState,
1397
+ muted: track.muted,
1398
+ label: track.label
1399
+ });
1400
+
1401
+ // Add track event listeners for state monitoring
1402
+ track.addEventListener('ended', () => {
1403
+ console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} ENDED`);
1404
+ });
1405
+
1406
+ track.addEventListener('mute', () => {
1407
+ console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} MUTED`);
1408
+ });
1409
+
1410
+ track.addEventListener('unmute', () => {
1411
+ console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} UNMUTED`);
1412
+ });
1413
+ });
1414
+
1415
+ this.displayRemoteVideo(peerId, stream);
1416
+
1417
+ // Audio data summary
1418
+ const audioSummary = {
1419
+ peerIdShort: peerId.substring(0, 8),
1420
+ audioTrackCount: audioTracks.length,
1421
+ videoTrackCount: videoTracks.length,
1422
+ audioTracksEnabled: audioTracks.filter(t => t.enabled).length,
1423
+ streamActive: stream.active,
1424
+ streamId: stream.id
1425
+ };
1426
+
1427
+ console.log(`🎵 AUDIO DATA EXPECTATION for peer ${audioSummary.peerIdShort}:`, audioSummary);
1428
+
1429
+ if (audioTracks.length > 0) {
1430
+ console.log(`✅ EXPECTING AUDIO DATA from peer ${audioSummary.peerIdShort} - ${audioSummary.audioTracksEnabled}/${audioSummary.audioTrackCount} tracks enabled`);
1431
+ } else {
1432
+ console.log(`❌ NO AUDIO TRACKS from peer ${audioSummary.peerIdShort} - video only`);
1433
+ }
1434
+
1435
+ this.addMessage('System', `🎵 Remote stream received from ${peerId.substring(0, 8)}... (${audioTracks.length} audio, ${videoTracks.length} video)`);
1436
+ }
1437
+
1438
+ displayRemoteVideo(peerId, stream) {
1439
+ console.log(`Displaying remote video for ${peerId}:`, stream);
1440
+ console.log('Stream tracks:', stream.getTracks().map(t => ({ kind: t.kind, enabled: t.enabled })));
1441
+
1442
+ // CRITICAL: Prevent audio loopback - check if this is our own stream
1443
+ const isOwnStream = peerId === this.mesh.peerId;
1444
+ if (isOwnStream) {
1445
+ console.warn('🚨 LOOPBACK DETECTED: Received our own stream! Muting audio to prevent feedback.');
1446
+ }
1447
+
1448
+ const remoteVideosContainer = document.getElementById('remote-videos-container');
1449
+ if (!remoteVideosContainer) return;
1450
+
1451
+ let remoteVideoItem = remoteVideosContainer.querySelector(`[data-peer-id="${peerId}"]`);
1452
+
1453
+ if (!remoteVideoItem) {
1454
+ remoteVideoItem = document.createElement('div');
1455
+ remoteVideoItem.className = 'remote-video-item';
1456
+ remoteVideoItem.setAttribute('data-peer-id', peerId);
1457
+
1458
+ const title = document.createElement('div');
1459
+ title.className = 'video-title';
1460
+ title.textContent = `Peer ${peerId.substring(0, 8)}...`;
1461
+
1462
+ const video = document.createElement('video');
1463
+ video.autoplay = true;
1464
+ video.playsInline = true;
1465
+ video.controls = true;
1466
+ // CRITICAL: Mute if this is our own stream to prevent audio feedback
1467
+ video.muted = isOwnStream; // Mute our own audio, unmute others
1468
+ video.style.width = '100%';
1469
+ video.style.borderRadius = '8px';
1470
+
1471
+ // Enhanced audio debugging
1472
+ video.addEventListener('loadedmetadata', () => {
1473
+ console.log('Video element loaded metadata:', {
1474
+ duration: video.duration,
1475
+ audioTracks: video.audioTracks?.length || 'N/A',
1476
+ volume: video.volume,
1477
+ muted: video.muted
1234
1478
  });
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
-
1272
- } catch (audioAnalysisError) {
1273
- console.log('Could not analyze remote audio:', audioAnalysisError);
1274
- }
1275
- } catch (e) {
1276
- console.log('Could not create/resume audio context:', e);
1277
- }
1479
+
1480
+ video.play().then(() => {
1481
+ console.log('Video/audio playback started successfully');
1482
+ // Check audio context state
1483
+ if (window.AudioContext || window.webkitAudioContext) {
1484
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
1485
+ const audioContext = new AudioContext();
1486
+ console.log('Audio context state:', audioContext.state);
1487
+ if (audioContext.state === 'suspended') {
1488
+ console.log('Audio context is suspended - may need user interaction');
1489
+ }
1490
+ }
1491
+ // Hide any play button if playback started
1492
+ const playButton = remoteVideoItem.querySelector('.manual-play-button');
1493
+ if (playButton) {
1494
+ playButton.style.display = 'none';
1495
+ }
1496
+ }).catch(error => {
1497
+ console.log('Autoplay failed, user interaction required:', error);
1498
+ // Show a manual play button
1499
+ const playButton = document.createElement('button');
1500
+ playButton.className = 'manual-play-button';
1501
+ playButton.textContent = '▶ Click to Play Audio';
1502
+ 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;';
1503
+
1504
+ playButton.addEventListener('click', async () => {
1505
+ try {
1506
+ await video.play();
1507
+ playButton.style.display = 'none';
1508
+ console.log('Manual play successful');
1509
+ } catch (e) {
1510
+ console.error('Manual play failed:', e);
1278
1511
  }
1512
+ });
1513
+
1514
+ remoteVideoItem.style.position = 'relative';
1515
+ remoteVideoItem.appendChild(playButton);
1516
+ });
1517
+ });
1518
+
1519
+ // Add event listeners for audio debugging
1520
+ video.addEventListener('play', () => {
1521
+ console.log('Video element started playing');
1522
+ });
1523
+
1524
+ video.addEventListener('pause', () => {
1525
+ console.log('Video element paused');
1526
+ });
1527
+
1528
+ video.addEventListener('volumechange', () => {
1529
+ console.log('Volume changed:', video.volume, 'Muted:', video.muted);
1530
+ });
1531
+
1532
+ const status = document.createElement('div');
1533
+ status.className = 'video-status';
1534
+
1535
+ remoteVideoItem.appendChild(title);
1536
+ remoteVideoItem.appendChild(video);
1537
+ remoteVideoItem.appendChild(status);
1538
+
1539
+ remoteVideosContainer.appendChild(remoteVideoItem);
1540
+ }
1541
+
1542
+ const video = remoteVideoItem.querySelector('video');
1543
+ const status = remoteVideoItem.querySelector('.video-status');
1544
+
1545
+ video.srcObject = stream;
1546
+
1547
+ // EXPLICIT AUDIO DEBUGGING
1548
+ console.log('🎵 Setting srcObject for video element:', {
1549
+ stream,
1550
+ streamId: stream.id,
1551
+ streamActive: stream.active,
1552
+ videoElement: video,
1553
+ videoMuted: video.muted,
1554
+ videoVolume: video.volume,
1555
+ isOwnStream
1556
+ });
1557
+
1558
+ const audioTracks = stream.getAudioTracks();
1559
+ const videoTracks = stream.getVideoTracks();
1560
+
1561
+ console.log('🎵 Stream tracks assigned:', {
1562
+ audioTracks: audioTracks.map(t => ({
1563
+ id: t.id,
1564
+ enabled: t.enabled,
1565
+ readyState: t.readyState,
1566
+ muted: t.muted
1567
+ })),
1568
+ videoTracks: videoTracks.map(t => ({
1569
+ id: t.id,
1570
+ enabled: t.enabled,
1571
+ readyState: t.readyState,
1572
+ muted: t.muted
1573
+ }))
1574
+ });
1575
+
1576
+ // CRITICAL: Set audio state based on whether this is our own stream
1577
+ if (isOwnStream) {
1578
+ console.warn('🚨 Muting our own stream to prevent audio feedback');
1579
+ video.muted = true;
1580
+ video.volume = 0;
1581
+ } else {
1582
+ // Only unmute if this is NOT our own stream
1583
+ video.muted = false;
1584
+ video.volume = 1.0;
1585
+
1586
+ // Setup audio playback monitoring for remote streams
1587
+ this.setupAudioPlaybackMonitoring(video, peerId, audioTracks);
1588
+ }
1589
+
1590
+ // Update status based on stream tracks
1591
+ console.log(`Video tracks: ${videoTracks.length}, Audio tracks: ${audioTracks.length}`);
1592
+ audioTracks.forEach((track, i) => {
1593
+ console.log(`Audio track ${i}:`, { enabled: track.enabled, muted: track.muted, label: track.label });
1594
+ });
1595
+
1596
+ // For audio-only streams, ensure the video element is properly configured
1597
+ if (audioTracks.length > 0 && videoTracks.length === 0) {
1598
+ console.log('Audio-only stream detected - configuring for audio playback');
1599
+ video.style.height = '60px'; // Smaller height for audio-only
1600
+ video.style.backgroundColor = '#f0f0f0';
1601
+
1602
+ // Force audio to play by trying to resume audio context
1603
+ if (window.AudioContext || window.webkitAudioContext) {
1604
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
1605
+ try {
1606
+ const audioContext = new AudioContext();
1607
+ if (audioContext.state === 'suspended') {
1608
+ audioContext.resume().then(() => {
1609
+ console.log('Audio context resumed for remote stream');
1610
+ });
1611
+ }
1612
+
1613
+ // Test audio by creating a brief analysis
1614
+ try {
1615
+ const source = audioContext.createMediaStreamSource(stream);
1616
+ const analyser = audioContext.createAnalyser();
1617
+ source.connect(analyser);
1618
+
1619
+ const dataArray = new Uint8Array(analyser.frequencyBinCount);
1620
+ const checkAudio = () => {
1621
+ analyser.getByteFrequencyData(dataArray);
1622
+ const sum = dataArray.reduce((a, b) => a + b, 0);
1623
+ if (sum > 0) {
1624
+ console.log('Remote audio data detected! Sum:', sum);
1625
+ }
1626
+ };
1627
+
1628
+ // Check audio data periodically
1629
+ const audioChecker = setInterval(checkAudio, 1000);
1630
+ setTimeout(() => clearInterval(audioChecker), 10000); // Stop after 10 seconds
1631
+ } catch (audioAnalysisError) {
1632
+ console.log('Could not analyze remote audio:', audioAnalysisError);
1633
+ }
1634
+ } catch (e) {
1635
+ console.log('Could not create/resume audio context:', e);
1279
1636
  }
1280
-
1281
- const statusText = [];
1282
- if (videoTracks.length > 0) statusText.push('Video');
1283
- if (audioTracks.length > 0) statusText.push('Audio');
1284
-
1285
- status.textContent = statusText.length > 0 ? statusText.join(' + ') : 'Audio only';
1286
- status.style.color = '#28a745';
1287
-
1288
- this.addMessage('System', `Receiving ${statusText.join(' + ')} from ${peerId.substring(0, 8)}...`);
1289
- }
1290
-
1291
- /**
1637
+ }
1638
+ }
1639
+
1640
+ const statusText = [];
1641
+ if (videoTracks.length > 0) statusText.push('Video');
1642
+ if (audioTracks.length > 0) statusText.push('Audio');
1643
+
1644
+ status.textContent = statusText.length > 0 ? statusText.join(' + ') : 'Audio only';
1645
+ status.style.color = '#28a745';
1646
+
1647
+ this.addMessage('System', `Receiving ${statusText.join(' + ')} from ${peerId.substring(0, 8)}...`);
1648
+ }
1649
+
1650
+ /**
1292
1651
  * Setup audio playback monitoring for video elements playing remote streams
1293
1652
  */
1294
- setupAudioPlaybackMonitoring(videoElement, peerId, audioTracks) {
1295
- const peerIdShort = peerId.substring(0, 8);
1296
- console.log(`🎵 Setting up audio playback monitoring for peer ${peerIdShort}`);
1297
-
1298
- if (audioTracks.length === 0) {
1299
- console.log(`🎵 No audio tracks to monitor for peer ${peerIdShort}`);
1300
- return;
1301
- }
1302
-
1653
+ setupAudioPlaybackMonitoring(videoElement, peerId, audioTracks) {
1654
+ const peerIdShort = peerId.substring(0, 8);
1655
+ console.log(`🎵 Setting up audio playback monitoring for peer ${peerIdShort}`);
1656
+
1657
+ if (audioTracks.length === 0) {
1658
+ console.log(`🎵 No audio tracks to monitor for peer ${peerIdShort}`);
1659
+ return;
1660
+ }
1661
+
1662
+ try {
1663
+ // Monitor video element audio events
1664
+ videoElement.addEventListener('play', () => {
1665
+ console.log(`🎵 Video element started playing for peer ${peerIdShort}`, {
1666
+ muted: videoElement.muted,
1667
+ volume: videoElement.volume,
1668
+ audioTracks: audioTracks.length
1669
+ });
1670
+ });
1671
+
1672
+ videoElement.addEventListener('pause', () => {
1673
+ console.log(`🎵 Video element paused for peer ${peerIdShort}`);
1674
+ });
1675
+
1676
+ videoElement.addEventListener('volumechange', () => {
1677
+ console.log(`🎵 Volume changed for peer ${peerIdShort}:`, {
1678
+ volume: videoElement.volume,
1679
+ muted: videoElement.muted
1680
+ });
1681
+ });
1682
+
1683
+ // Create audio context for monitoring actual audio data playback
1684
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
1685
+ if (!AudioContext) {
1686
+ console.warn('🎵 AudioContext not available - basic monitoring only');
1687
+ return;
1688
+ }
1689
+
1690
+ // Wait for video to load before setting up audio analysis
1691
+ const setupAudioAnalysis = () => {
1303
1692
  try {
1304
- // Monitor video element audio events
1305
- videoElement.addEventListener('play', () => {
1306
- console.log(`🎵 Video element started playing for peer ${peerIdShort}`, {
1307
- muted: videoElement.muted,
1308
- volume: videoElement.volume,
1309
- audioTracks: audioTracks.length
1310
- });
1311
- });
1312
-
1313
- videoElement.addEventListener('pause', () => {
1314
- console.log(`🎵 Video element paused for peer ${peerIdShort}`);
1315
- });
1316
-
1317
- videoElement.addEventListener('volumechange', () => {
1318
- console.log(`🎵 Volume changed for peer ${peerIdShort}:`, {
1319
- volume: videoElement.volume,
1320
- muted: videoElement.muted
1321
- });
1322
- });
1323
-
1324
- // Create audio context for monitoring actual audio data playback
1325
- const AudioContext = window.AudioContext || window.webkitAudioContext;
1326
- if (!AudioContext) {
1327
- console.warn('🎵 AudioContext not available - basic monitoring only');
1328
- return;
1693
+ const audioContext = new AudioContext();
1694
+ const source = audioContext.createMediaElementSource(videoElement);
1695
+ const analyser = audioContext.createAnalyser();
1696
+ const gainNode = audioContext.createGain();
1697
+
1698
+ analyser.fftSize = 256;
1699
+ const bufferLength = analyser.frequencyBinCount;
1700
+ const dataArray = new Uint8Array(bufferLength);
1701
+
1702
+ // Connect: source -> analyser -> gain -> destination
1703
+ source.connect(analyser);
1704
+ analyser.connect(gainNode);
1705
+ gainNode.connect(audioContext.destination);
1706
+
1707
+ let lastLogTime = 0;
1708
+ let totalSamples = 0;
1709
+ let playbackSamples = 0;
1710
+ let maxPlaybackLevel = 0;
1711
+
1712
+ const monitorPlayback = () => {
1713
+ if (videoElement.paused || videoElement.ended) {
1714
+ return; // Stop monitoring if playback stopped
1329
1715
  }
1330
-
1331
- // Wait for video to load before setting up audio analysis
1332
- const setupAudioAnalysis = () => {
1333
- try {
1334
- const audioContext = new AudioContext();
1335
- const source = audioContext.createMediaElementSource(videoElement);
1336
- const analyser = audioContext.createAnalyser();
1337
- const gainNode = audioContext.createGain();
1338
-
1339
- analyser.fftSize = 256;
1340
- const bufferLength = analyser.frequencyBinCount;
1341
- const dataArray = new Uint8Array(bufferLength);
1342
-
1343
- // Connect: source -> analyser -> gain -> destination
1344
- source.connect(analyser);
1345
- analyser.connect(gainNode);
1346
- gainNode.connect(audioContext.destination);
1347
-
1348
- let lastLogTime = 0;
1349
- let totalSamples = 0;
1350
- let playbackSamples = 0;
1351
- let maxPlaybackLevel = 0;
1352
-
1353
- const monitorPlayback = () => {
1354
- if (videoElement.paused || videoElement.ended) {
1355
- return; // Stop monitoring if playback stopped
1356
- }
1357
-
1358
- analyser.getByteFrequencyData(dataArray);
1359
-
1360
- // Calculate playback audio level
1361
- const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
1362
- const currentTime = Date.now();
1363
-
1364
- totalSamples++;
1365
- if (average > 3) { // Lower threshold for playback detection
1366
- playbackSamples++;
1367
- maxPlaybackLevel = Math.max(maxPlaybackLevel, average);
1368
- }
1369
-
1370
- // Log every 3 seconds
1371
- if (currentTime - lastLogTime > 3000) {
1372
- const playbackActivity = totalSamples > 0 ? (playbackSamples / totalSamples * 100) : 0;
1373
- console.log(`🔊 Audio PLAYBACK from peer ${peerIdShort}:`, {
1374
- videoElementMuted: videoElement.muted,
1375
- videoElementVolume: videoElement.volume,
1376
- currentPlaybackLevel: Math.round(average),
1377
- maxPlaybackLevel: Math.round(maxPlaybackLevel),
1378
- playbackActivityPercent: Math.round(playbackActivity),
1379
- samplesAnalyzed: totalSamples,
1380
- audioBeingPlayed: playbackSamples > 0,
1381
- audioContextState: audioContext.state
1382
- });
1383
-
1384
- lastLogTime = currentTime;
1385
- totalSamples = 0;
1386
- playbackSamples = 0;
1387
- maxPlaybackLevel = 0;
1388
- }
1389
-
1390
- // Continue monitoring
1391
- if (!videoElement.paused && !videoElement.ended) {
1392
- requestAnimationFrame(monitorPlayback);
1393
- }
1394
- };
1395
-
1396
- // Start monitoring when video plays
1397
- videoElement.addEventListener('play', () => {
1398
- console.log(`🔊 Starting audio playback monitoring for peer ${peerIdShort}`);
1399
- if (audioContext.state === 'suspended') {
1400
- audioContext.resume().then(() => {
1401
- requestAnimationFrame(monitorPlayback);
1402
- });
1403
- } else {
1404
- requestAnimationFrame(monitorPlayback);
1405
- }
1406
- });
1407
-
1408
- console.log(`🔊 Audio playback analysis setup complete for peer ${peerIdShort}`);
1409
-
1410
- } catch (error) {
1411
- console.error(`🔊 Failed to setup audio playback analysis for peer ${peerIdShort}:`, error);
1412
- }
1413
- };
1414
-
1415
- if (videoElement.readyState >= 1) {
1416
- // Video metadata already loaded
1417
- setupAudioAnalysis();
1716
+
1717
+ analyser.getByteFrequencyData(dataArray);
1718
+
1719
+ // Calculate playback audio level
1720
+ const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
1721
+ const currentTime = Date.now();
1722
+
1723
+ totalSamples++;
1724
+ if (average > 3) { // Lower threshold for playback detection
1725
+ playbackSamples++;
1726
+ maxPlaybackLevel = Math.max(maxPlaybackLevel, average);
1727
+ }
1728
+
1729
+ // Log every 3 seconds
1730
+ if (currentTime - lastLogTime > 3000) {
1731
+ const playbackActivity = totalSamples > 0 ? (playbackSamples / totalSamples * 100) : 0;
1732
+ console.log(`🔊 Audio PLAYBACK from peer ${peerIdShort}:`, {
1733
+ videoElementMuted: videoElement.muted,
1734
+ videoElementVolume: videoElement.volume,
1735
+ currentPlaybackLevel: Math.round(average),
1736
+ maxPlaybackLevel: Math.round(maxPlaybackLevel),
1737
+ playbackActivityPercent: Math.round(playbackActivity),
1738
+ samplesAnalyzed: totalSamples,
1739
+ audioBeingPlayed: playbackSamples > 0,
1740
+ audioContextState: audioContext.state
1741
+ });
1742
+
1743
+ lastLogTime = currentTime;
1744
+ totalSamples = 0;
1745
+ playbackSamples = 0;
1746
+ maxPlaybackLevel = 0;
1747
+ }
1748
+
1749
+ // Continue monitoring
1750
+ if (!videoElement.paused && !videoElement.ended) {
1751
+ requestAnimationFrame(monitorPlayback);
1752
+ }
1753
+ };
1754
+
1755
+ // Start monitoring when video plays
1756
+ videoElement.addEventListener('play', () => {
1757
+ console.log(`🔊 Starting audio playback monitoring for peer ${peerIdShort}`);
1758
+ if (audioContext.state === 'suspended') {
1759
+ audioContext.resume().then(() => {
1760
+ requestAnimationFrame(monitorPlayback);
1761
+ });
1418
1762
  } else {
1419
- // Wait for metadata to load
1420
- videoElement.addEventListener('loadedmetadata', setupAudioAnalysis, { once: true });
1763
+ requestAnimationFrame(monitorPlayback);
1421
1764
  }
1422
-
1765
+ });
1766
+
1767
+ console.log(`🔊 Audio playback analysis setup complete for peer ${peerIdShort}`);
1423
1768
  } catch (error) {
1424
- console.error(`🎵 Failed to setup audio playback monitoring for peer ${peerIdShort}:`, error);
1769
+ console.error(`🔊 Failed to setup audio playback analysis for peer ${peerIdShort}:`, error);
1425
1770
  }
1771
+ };
1772
+
1773
+ if (videoElement.readyState >= 1) {
1774
+ // Video metadata already loaded
1775
+ setupAudioAnalysis();
1776
+ } else {
1777
+ // Wait for metadata to load
1778
+ videoElement.addEventListener('loadedmetadata', setupAudioAnalysis, { once: true });
1779
+ }
1780
+ } catch (error) {
1781
+ console.error(`🎵 Failed to setup audio playback monitoring for peer ${peerIdShort}:`, error);
1426
1782
  }
1783
+ }
1427
1784
 
1428
- /**
1785
+ /**
1429
1786
  * Diagnostic method to log complete peer connection state
1430
1787
  */
1431
- logPeerDiagnostics() {
1432
- console.log('🔍 PEER DIAGNOSTICS:');
1433
- const allPeers = this.mesh.getPeers();
1434
-
1435
- console.log(`📊 Total peers in mesh: ${allPeers.length}`);
1436
-
1437
- allPeers.forEach((peer, index) => {
1438
- const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
1439
-
1440
- console.log(`\n🔍 Peer ${index + 1}: ${peer.peerId.substring(0, 8)}...`);
1441
- console.log(` Status: ${peer.status}`);
1442
-
1443
- if (peerConnection) {
1444
- console.log(` WebRTC Connection State: ${peerConnection.connection?.connectionState || 'none'}`);
1445
- console.log(` ICE Connection State: ${peerConnection.connection?.iceConnectionState || 'none'}`);
1446
- console.log(` Data Channel State: ${peerConnection.dataChannel?.readyState || 'none'}`);
1447
- console.log(` Data Channel Ready: ${peerConnection.dataChannelReady}`);
1448
- console.log(` Has Local Stream: ${!!peerConnection.localStream}`);
1449
- console.log(` Has Remote Stream: ${!!peerConnection.remoteStream}`);
1450
-
1451
- if (peerConnection.localStream) {
1452
- const audioTracks = peerConnection.localStream.getAudioTracks();
1453
- const videoTracks = peerConnection.localStream.getVideoTracks();
1454
- console.log(` Local Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
1455
- }
1456
-
1457
- if (peerConnection.remoteStream) {
1458
- const audioTracks = peerConnection.remoteStream.getAudioTracks();
1459
- const videoTracks = peerConnection.remoteStream.getVideoTracks();
1460
- console.log(` Remote Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
1461
- }
1462
- } else {
1463
- console.log(` ❌ No PeerConnection object found`);
1464
- }
1465
- });
1466
-
1467
- console.log('\n🔍 END PEER DIAGNOSTICS\n');
1468
- }
1469
-
1470
- // Existing UI methods (keeping the rest of the original functionality)
1471
- async handleConnect() {
1472
- const url = document.getElementById('signaling-url').value.trim();
1473
- if (!url) {
1474
- this.addMessage('System', 'Please enter a signaling server URL', 'error');
1475
- return;
1788
+ logPeerDiagnostics() {
1789
+ console.log('🔍 PEER DIAGNOSTICS:');
1790
+ const allPeers = this.mesh.getPeers();
1791
+
1792
+ console.log(`📊 Total peers in mesh: ${allPeers.length}`);
1793
+
1794
+ allPeers.forEach((peer, index) => {
1795
+ const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
1796
+
1797
+ console.log(`\n🔍 Peer ${index + 1}: ${peer.peerId.substring(0, 8)}...`);
1798
+ console.log(` Status: ${peer.status}`);
1799
+
1800
+ if (peerConnection) {
1801
+ console.log(` WebRTC Connection State: ${peerConnection.connection?.connectionState || 'none'}`);
1802
+ console.log(` ICE Connection State: ${peerConnection.connection?.iceConnectionState || 'none'}`);
1803
+ console.log(` Data Channel State: ${peerConnection.dataChannel?.readyState || 'none'}`);
1804
+ console.log(` Data Channel Ready: ${peerConnection.dataChannelReady}`);
1805
+ console.log(` Has Local Stream: ${!!peerConnection.localStream}`);
1806
+ console.log(` Has Remote Stream: ${!!peerConnection.remoteStream}`);
1807
+
1808
+ if (peerConnection.localStream) {
1809
+ const audioTracks = peerConnection.localStream.getAudioTracks();
1810
+ const videoTracks = peerConnection.localStream.getVideoTracks();
1811
+ console.log(` Local Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
1476
1812
  }
1477
1813
 
1478
- try {
1479
- this.updateButtonStates({ connecting: true });
1480
- await this.mesh.connect(url);
1481
- } catch (error) {
1482
- console.error('Connection failed:', error);
1483
- this.addMessage('System', `Connection failed: ${error.message}`, 'error');
1484
- this.updateButtonStates({ connecting: false });
1814
+ if (peerConnection.remoteStream) {
1815
+ const audioTracks = peerConnection.remoteStream.getAudioTracks();
1816
+ const videoTracks = peerConnection.remoteStream.getVideoTracks();
1817
+ console.log(` Remote Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
1485
1818
  }
1819
+ } else {
1820
+ console.log(' ❌ No PeerConnection object found');
1821
+ }
1822
+ });
1823
+
1824
+ console.log('\n🔍 END PEER DIAGNOSTICS\n');
1825
+ }
1826
+
1827
+ // Existing UI methods (keeping the rest of the original functionality)
1828
+ async handleConnect() {
1829
+ const url = document.getElementById('signaling-url').value.trim();
1830
+ if (!url) {
1831
+ this.addMessage('System', 'Please enter a signaling server URL', 'error');
1832
+ return;
1486
1833
  }
1487
1834
 
1488
- async handleDisconnect() {
1489
- try {
1490
- this.updateButtonStates({ disconnecting: true });
1491
- await this.mesh.disconnect();
1492
- } catch (error) {
1493
- console.error('Disconnection failed:', error);
1494
- this.addMessage('System', `Disconnection failed: ${error.message}`, 'error');
1495
- } finally {
1496
- this.updateButtonStates({ disconnecting: false });
1497
- }
1835
+ try {
1836
+ this.updateButtonStates({ connecting: true });
1837
+ await this.mesh.connect(url);
1838
+ } catch (error) {
1839
+ console.error('Connection failed:', error);
1840
+ this.addMessage('System', `Connection failed: ${error.message}`, 'error');
1841
+ this.updateButtonStates({ connecting: false });
1842
+ }
1843
+ }
1844
+
1845
+ async handleDisconnect() {
1846
+ try {
1847
+ this.updateButtonStates({ disconnecting: true });
1848
+ await this.mesh.disconnect();
1849
+ } catch (error) {
1850
+ console.error('Disconnection failed:', error);
1851
+ this.addMessage('System', `Disconnection failed: ${error.message}`, 'error');
1852
+ } finally {
1853
+ this.updateButtonStates({ disconnecting: false });
1498
1854
  }
1855
+ }
1499
1856
 
1500
- async handleCleanup() {
1501
- const now = Date.now();
1502
- const timeSinceLastCleanup = now - this.lastCleanupTime;
1503
-
1504
- if (timeSinceLastCleanup < 5000) {
1505
- const remaining = Math.ceil((5000 - timeSinceLastCleanup) / 1000);
1506
- this.addMessage('System', `Cleanup on cooldown (${remaining}s remaining)`, 'warning');
1507
- return;
1508
- }
1857
+ async handleCleanup() {
1858
+ const now = Date.now();
1859
+ const timeSinceLastCleanup = now - this.lastCleanupTime;
1509
1860
 
1510
- try {
1511
- this.lastCleanupTime = now;
1512
- await this.mesh.cleanupSignalingData();
1513
- this.addMessage('System', 'Signaling data cleanup initiated');
1514
- } catch (error) {
1515
- console.error('Cleanup failed:', error);
1516
- this.addMessage('System', `Cleanup failed: ${error.message}`, 'error');
1517
- }
1861
+ if (timeSinceLastCleanup < 5000) {
1862
+ const remaining = Math.ceil((5000 - timeSinceLastCleanup) / 1000);
1863
+ this.addMessage('System', `Cleanup on cooldown (${remaining}s remaining)`, 'warning');
1864
+ return;
1518
1865
  }
1519
1866
 
1520
- async handleHealthCheck() {
1521
- try {
1522
- const result = await this.mesh.performHealthCheck();
1523
- if (result.healthy) {
1524
- this.addMessage('System', 'Health check passed - all systems nominal', 'info');
1525
- } else {
1526
- this.addMessage('System', `Health check failed: ${result.issues.join(', ')}`, 'warning');
1527
- }
1528
- } catch (error) {
1529
- console.error('Health check failed:', error);
1530
- this.addMessage('System', `Health check error: ${error.message}`, 'error');
1531
- }
1867
+ try {
1868
+ this.lastCleanupTime = now;
1869
+ await this.mesh.cleanupSignalingData();
1870
+ this.addMessage('System', 'Signaling data cleanup initiated');
1871
+ } catch (error) {
1872
+ console.error('Cleanup failed:', error);
1873
+ this.addMessage('System', `Cleanup failed: ${error.message}`, 'error');
1874
+ }
1875
+ }
1876
+
1877
+ async handleHealthCheck() {
1878
+ try {
1879
+ const result = await this.mesh.performHealthCheck();
1880
+ if (result.healthy) {
1881
+ this.addMessage('System', 'Health check passed - all systems nominal', 'info');
1882
+ } else {
1883
+ this.addMessage('System', `Health check failed: ${result.issues.join(', ')}`, 'warning');
1884
+ }
1885
+ } catch (error) {
1886
+ console.error('Health check failed:', error);
1887
+ this.addMessage('System', `Health check error: ${error.message}`, 'error');
1532
1888
  }
1889
+ }
1533
1890
 
1534
- sendMessage() {
1535
- const messageInput = document.getElementById('message-input');
1536
- const dmTargetInput = document.getElementById('dm-target-input');
1537
- const message = messageInput.value.trim();
1538
- const dmTarget = dmTargetInput.value.trim();
1891
+ async sendMessage() {
1892
+ const messageInput = document.getElementById('message-input');
1893
+ const dmTargetInput = document.getElementById('dm-target-input');
1894
+ const autoEncryptToggle = document.getElementById('crypto-auto-encrypt');
1539
1895
 
1540
- if (!message) return;
1896
+ if (!messageInput) return;
1541
1897
 
1542
- try {
1543
- if (dmTarget) {
1544
- // Validate peer ID format
1545
- if (!window.PeerPigeonMesh.validatePeerId(dmTarget)) {
1546
- this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
1547
- return;
1548
- }
1549
-
1550
- // Send direct message
1551
- const success = this.mesh.sendDirectMessage(dmTarget, message);
1552
- if (success) {
1553
- this.addMessage('You', `(DM to ${dmTarget.substring(0, 8)}...) ${message}`, 'own');
1554
- } else {
1555
- this.addMessage('System', `Failed to send direct message to ${dmTarget.substring(0, 8)}...`, 'error');
1556
- }
1557
- } else {
1558
- // Send broadcast message
1559
- // this.mesh.broadcastMessage(message);
1560
- this.mesh.sendMessage(message);
1561
- this.addMessage('You', message, 'own');
1562
- }
1898
+ const message = messageInput.value.trim();
1899
+ const dmTarget = dmTargetInput ? dmTargetInput.value.trim() : '';
1563
1900
 
1564
- messageInput.value = '';
1565
- } catch (error) {
1566
- console.error('Failed to send message:', error);
1567
- this.addMessage('System', `Failed to send message: ${error.message}`, 'error');
1568
- }
1569
- }
1901
+ if (!message) return;
1570
1902
 
1571
- connectToPeer() {
1572
- const targetPeerInput = document.getElementById('target-peer');
1573
- const targetPeerId = targetPeerInput.value.trim();
1903
+ try {
1904
+ // Check if auto-encrypt is enabled and crypto is available
1905
+ const shouldEncrypt = autoEncryptToggle && autoEncryptToggle.checked && this.mesh.getCryptoStatus().enabled;
1574
1906
 
1575
- if (!targetPeerId) {
1576
- this.addMessage('System', 'Please enter a peer ID', 'error');
1577
- return;
1907
+ if (dmTarget) {
1908
+ // Validate peer ID format for direct messages
1909
+ if (!window.PeerPigeonMesh.validatePeerId(dmTarget)) {
1910
+ this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
1911
+ return;
1578
1912
  }
1579
1913
 
1580
- if (!window.PeerPigeonMesh.validatePeerId(targetPeerId)) {
1581
- this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
1582
- return;
1914
+ // Send direct message (encrypted or not)
1915
+ if (shouldEncrypt) {
1916
+ await this.mesh.sendEncryptedMessage(dmTarget, message);
1917
+ this.addMessage('You', `🔐 (DM to ${dmTarget.substring(0, 8)}...) ${message}`, 'encrypted');
1918
+ } else {
1919
+ const success = this.mesh.sendDirectMessage(dmTarget, message);
1920
+ if (success) {
1921
+ this.addMessage('You', `(DM to ${dmTarget.substring(0, 8)}...) ${message}`, 'own');
1922
+ } else {
1923
+ this.addMessage('System', `Failed to send direct message to ${dmTarget.substring(0, 8)}...`, 'error');
1924
+ }
1583
1925
  }
1584
-
1585
- if (targetPeerId === this.mesh.peerId) {
1586
- this.addMessage('System', 'Cannot connect to yourself', 'error');
1587
- return;
1926
+ } else {
1927
+ // Send broadcast message (encrypted or not)
1928
+ if (shouldEncrypt) {
1929
+ // Get all connected peers for encryption
1930
+ const connectedPeers = this.mesh.getPeers();
1931
+ if (connectedPeers.length > 0) {
1932
+ // Send encrypted message to all connected peers
1933
+ for (const peer of connectedPeers) {
1934
+ try {
1935
+ await this.mesh.sendEncryptedMessage(peer.peerId, message);
1936
+ } catch (error) {
1937
+ console.warn(`Failed to send encrypted message to ${peer.peerId}:`, error);
1938
+ }
1939
+ }
1940
+ this.addMessage('You', `🔐 ${message}`, 'encrypted');
1941
+ } else {
1942
+ this.addMessage('System', 'No connected peers to send encrypted message to', 'error');
1943
+ }
1944
+ } else {
1945
+ // Send regular unencrypted message
1946
+ this.mesh.sendMessage(message);
1947
+ this.addMessage('You', message, 'own');
1588
1948
  }
1949
+ }
1589
1950
 
1590
- try {
1591
- this.mesh.connectToPeer(targetPeerId);
1592
- this.addMessage('System', `Attempting to connect to ${targetPeerId.substring(0, 8)}...`);
1593
- targetPeerInput.value = '';
1594
- } catch (error) {
1595
- console.error('Failed to initiate connection:', error);
1596
- this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
1597
- }
1951
+ messageInput.value = '';
1952
+ } catch (error) {
1953
+ console.error('Failed to send message:', error);
1954
+ this.addMessage('System', `Failed to send message: ${error.message}`, 'error');
1598
1955
  }
1956
+ }
1599
1957
 
1600
- /**
1958
+ connectToPeer() {
1959
+ const targetPeerInput = document.getElementById('target-peer');
1960
+ const targetPeerId = targetPeerInput.value.trim();
1961
+
1962
+ if (!targetPeerId) {
1963
+ this.addMessage('System', 'Please enter a peer ID', 'error');
1964
+ return;
1965
+ }
1966
+
1967
+ if (!window.PeerPigeonMesh.validatePeerId(targetPeerId)) {
1968
+ this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
1969
+ return;
1970
+ }
1971
+
1972
+ if (targetPeerId === this.mesh.peerId) {
1973
+ this.addMessage('System', 'Cannot connect to yourself', 'error');
1974
+ return;
1975
+ }
1976
+
1977
+ try {
1978
+ this.mesh.connectToPeer(targetPeerId);
1979
+ this.addMessage('System', `Attempting to connect to ${targetPeerId.substring(0, 8)}...`);
1980
+ targetPeerInput.value = '';
1981
+ } catch (error) {
1982
+ console.error('Failed to initiate connection:', error);
1983
+ this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
1984
+ }
1985
+ }
1986
+
1987
+ /**
1601
1988
  * Connect to peer from button click (for onclick handlers)
1602
1989
  */
1603
- connectToPeerFromButton(button) {
1604
- const peerId = button.getAttribute('data-peer-id');
1605
- if (!peerId) {
1606
- this.addMessage('System', 'Invalid peer ID in button', 'error');
1607
- return;
1608
- }
1609
-
1610
- // Disable button to prevent double-clicks
1611
- button.disabled = true;
1612
- button.textContent = 'Connecting...';
1613
-
1614
- try {
1615
- this.mesh.connectToPeer(peerId);
1616
- this.addMessage('System', `Attempting to connect to ${peerId.substring(0, 8)}...`);
1617
-
1618
- // Re-enable button after a delay
1619
- setTimeout(() => {
1620
- button.disabled = false;
1621
- button.textContent = 'Connect';
1622
- }, 3000);
1623
-
1624
- } catch (error) {
1625
- console.error('Failed to initiate connection:', error);
1626
- this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
1627
-
1628
- // Re-enable button immediately on error
1629
- button.disabled = false;
1630
- button.textContent = 'Connect';
1631
- }
1990
+ connectToPeerFromButton(button) {
1991
+ const peerId = button.getAttribute('data-peer-id');
1992
+ if (!peerId) {
1993
+ this.addMessage('System', 'Invalid peer ID in button', 'error');
1994
+ return;
1632
1995
  }
1633
1996
 
1634
- updateUI() {
1635
- // Update peer ID display
1636
- const peerIdElement = document.getElementById('peer-id');
1637
- if (peerIdElement && this.mesh.peerId) {
1638
- peerIdElement.textContent = this.mesh.peerId;
1639
- }
1997
+ // Disable button to prevent double-clicks
1998
+ button.disabled = true;
1999
+ button.textContent = 'Connecting...';
2000
+
2001
+ try {
2002
+ this.mesh.connectToPeer(peerId);
2003
+ this.addMessage('System', `Attempting to connect to ${peerId.substring(0, 8)}...`);
2004
+
2005
+ // Re-enable button after a delay
2006
+ setTimeout(() => {
2007
+ button.disabled = false;
2008
+ button.textContent = 'Connect';
2009
+ }, 3000);
2010
+ } catch (error) {
2011
+ console.error('Failed to initiate connection:', error);
2012
+ this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
2013
+
2014
+ // Re-enable button immediately on error
2015
+ button.disabled = false;
2016
+ button.textContent = 'Connect';
2017
+ }
2018
+ }
1640
2019
 
1641
- // Update status
1642
- this.updateStatus();
1643
-
1644
- // Update button states
1645
- this.updateButtonStates();
1646
-
1647
- // Update peer lists
1648
- this.updateConnectedPeers();
1649
- this.updateDiscoveredPeers();
1650
-
1651
- // Update settings from mesh state
1652
- this.updateSettings();
1653
-
1654
- // Update DHT status
1655
- this.updateDHTStatus();
2020
+ updateUI() {
2021
+ // Update peer ID display
2022
+ const peerIdElement = document.getElementById('peer-id');
2023
+ if (peerIdElement && this.mesh.peerId) {
2024
+ peerIdElement.textContent = this.mesh.peerId;
1656
2025
  }
1657
2026
 
1658
- updateStatus() {
1659
- const statusElement = document.getElementById('status');
1660
- if (!statusElement) return;
2027
+ // Update status
2028
+ this.updateStatus();
1661
2029
 
1662
- const status = this.mesh.getStatus();
1663
- const connectionStatus = status.connected ? 'connected' : 'disconnected';
1664
- statusElement.textContent = connectionStatus.charAt(0).toUpperCase() + connectionStatus.slice(1);
1665
- statusElement.className = `status ${connectionStatus.toLowerCase()}`;
1666
- }
2030
+ // Update button states
2031
+ this.updateButtonStates();
1667
2032
 
1668
- updateButtonStates(options = {}) {
1669
- const connectBtn = document.getElementById('connect-btn');
1670
- const disconnectBtn = document.getElementById('disconnect-btn');
1671
- const cleanupBtn = document.getElementById('cleanup-btn');
1672
- const healthCheckBtn = document.getElementById('health-check-btn');
2033
+ // Update peer lists
2034
+ this.updateConnectedPeers();
2035
+ this.updateDiscoveredPeers();
1673
2036
 
1674
- const isConnected = this.mesh.connected;
1675
- const isConnecting = options.connecting || false;
1676
- const isDisconnecting = options.disconnecting || false;
2037
+ // Update settings from mesh state
2038
+ this.updateSettings();
1677
2039
 
1678
- if (connectBtn) {
1679
- connectBtn.disabled = isConnected || isConnecting;
1680
- connectBtn.textContent = isConnecting ? 'Connecting...' : 'Connect';
1681
- }
2040
+ // Update DHT status
2041
+ this.updateDHTStatus();
2042
+ }
1682
2043
 
1683
- if (disconnectBtn) {
1684
- disconnectBtn.disabled = !isConnected || isDisconnecting;
1685
- disconnectBtn.textContent = isDisconnecting ? 'Disconnecting...' : 'Disconnect';
1686
- }
2044
+ updateStatus() {
2045
+ const statusElement = document.getElementById('status');
2046
+ if (!statusElement) return;
1687
2047
 
1688
- if (cleanupBtn) {
1689
- cleanupBtn.disabled = !isConnected;
1690
- }
2048
+ const status = this.mesh.getStatus();
2049
+ const connectionStatus = status.connected ? 'connected' : 'disconnected';
2050
+ statusElement.textContent = connectionStatus.charAt(0).toUpperCase() + connectionStatus.slice(1);
2051
+ statusElement.className = `status ${connectionStatus.toLowerCase()}`;
2052
+ }
1691
2053
 
1692
- if (healthCheckBtn) {
1693
- healthCheckBtn.disabled = !isConnected;
1694
- }
2054
+ updateButtonStates(options = {}) {
2055
+ const connectBtn = document.getElementById('connect-btn');
2056
+ const disconnectBtn = document.getElementById('disconnect-btn');
2057
+ const cleanupBtn = document.getElementById('cleanup-btn');
2058
+ const healthCheckBtn = document.getElementById('health-check-btn');
2059
+
2060
+ const isConnected = this.mesh.connected;
2061
+ const isConnecting = options.connecting || false;
2062
+ const isDisconnecting = options.disconnecting || false;
2063
+
2064
+ if (connectBtn) {
2065
+ connectBtn.disabled = isConnected || isConnecting;
2066
+ connectBtn.textContent = isConnecting ? 'Connecting...' : 'Connect';
1695
2067
  }
1696
2068
 
1697
- updateConnectedPeers() {
1698
- const peersList = document.getElementById('peers-list');
1699
- const connectedPeersCount = document.getElementById('connected-peers-count');
1700
-
1701
- if (!peersList || !connectedPeersCount) return;
2069
+ if (disconnectBtn) {
2070
+ disconnectBtn.disabled = !isConnected || isDisconnecting;
2071
+ disconnectBtn.textContent = isDisconnecting ? 'Disconnecting...' : 'Disconnect';
2072
+ }
1702
2073
 
1703
- const peers = this.mesh.getPeers();
1704
- connectedPeersCount.textContent = peers.length;
2074
+ if (cleanupBtn) {
2075
+ cleanupBtn.disabled = !isConnected;
2076
+ }
1705
2077
 
1706
- if (peers.length === 0) {
1707
- peersList.innerHTML = '<p class="empty-state">No peers connected</p>';
1708
- return;
1709
- }
2078
+ if (healthCheckBtn) {
2079
+ healthCheckBtn.disabled = !isConnected;
2080
+ }
2081
+ }
2082
+
2083
+ updateConnectedPeers() {
2084
+ const peersList = document.getElementById('peers-list');
2085
+ const connectedPeersCount = document.getElementById('connected-peers-count');
2086
+
2087
+ if (!peersList || !connectedPeersCount) return;
2088
+
2089
+ const peers = this.mesh.getPeers();
2090
+ connectedPeersCount.textContent = peers.length;
2091
+
2092
+ if (peers.length === 0) {
2093
+ peersList.innerHTML = '<p class="empty-state">No peers connected</p>';
2094
+ return;
2095
+ }
2096
+
2097
+ peersList.innerHTML = peers.map(peer => {
2098
+ // peer is a plain object: { peerId, status, isInitiator, connectionStartTime }
2099
+ const statusClass = peer.status === 'connected' ? 'connected' : 'connecting';
2100
+ const connectionTime = ((Date.now() - peer.connectionStartTime) / 1000).toFixed(1);
1710
2101
 
1711
- peersList.innerHTML = peers.map(peer => {
1712
- // peer is a plain object: { peerId, status, isInitiator, connectionStartTime }
1713
- const statusClass = peer.status === 'connected' ? 'connected' : 'connecting';
1714
- const connectionTime = ((Date.now() - peer.connectionStartTime) / 1000).toFixed(1);
1715
-
1716
- return `
2102
+ return `
1717
2103
  <div class="peer-item">
1718
2104
  <div class="peer-info">
1719
2105
  <span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
@@ -1725,36 +2111,36 @@ export class PeerPigeonUI {
1725
2111
  </div>
1726
2112
  </div>
1727
2113
  `;
1728
- }).join('');
1729
- }
1730
-
1731
- updateDiscoveredPeers() {
1732
- const discoveredPeersList = document.getElementById('discovered-peers-list');
1733
- const discoveredPeersCount = document.getElementById('discovered-peers-count');
1734
-
1735
- if (!discoveredPeersList || !discoveredPeersCount) return;
1736
-
1737
- const discoveredPeers = this.mesh.getDiscoveredPeers();
1738
- const connectedPeerIds = this.mesh.getPeers().map(p => p.peerId);
1739
-
1740
- // Filter out already connected peers
1741
- const availablePeers = discoveredPeers.filter(peer =>
1742
- !connectedPeerIds.includes(peer.peerId) && peer.peerId !== this.mesh.peerId
1743
- );
1744
-
1745
- discoveredPeersCount.textContent = availablePeers.length;
1746
-
1747
- if (availablePeers.length === 0) {
1748
- discoveredPeersList.innerHTML = '<p class="empty-state">No peers discovered</p>';
1749
- return;
1750
- }
2114
+ }).join('');
2115
+ }
2116
+
2117
+ updateDiscoveredPeers() {
2118
+ const discoveredPeersList = document.getElementById('discovered-peers-list');
2119
+ const discoveredPeersCount = document.getElementById('discovered-peers-count');
2120
+
2121
+ if (!discoveredPeersList || !discoveredPeersCount) return;
2122
+
2123
+ const discoveredPeers = this.mesh.getDiscoveredPeers();
2124
+ const connectedPeerIds = this.mesh.getPeers().map(p => p.peerId);
1751
2125
 
1752
- discoveredPeersList.innerHTML = availablePeers.map(peer => {
1753
- const lastSeen = peer.lastSeen ?
1754
- `${Math.round((Date.now() - peer.lastSeen) / 1000)}s ago` :
1755
- 'Unknown';
1756
-
1757
- return `
2126
+ // Filter out already connected peers
2127
+ const availablePeers = discoveredPeers.filter(peer =>
2128
+ !connectedPeerIds.includes(peer.peerId) && peer.peerId !== this.mesh.peerId
2129
+ );
2130
+
2131
+ discoveredPeersCount.textContent = availablePeers.length;
2132
+
2133
+ if (availablePeers.length === 0) {
2134
+ discoveredPeersList.innerHTML = '<p class="empty-state">No peers discovered</p>';
2135
+ return;
2136
+ }
2137
+
2138
+ discoveredPeersList.innerHTML = availablePeers.map(peer => {
2139
+ const lastSeen = peer.lastSeen
2140
+ ? `${Math.round((Date.now() - peer.lastSeen) / 1000)}s ago`
2141
+ : 'Unknown';
2142
+
2143
+ return `
1758
2144
  <div class="peer-item discovered">
1759
2145
  <div class="peer-info">
1760
2146
  <span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
@@ -1768,108 +2154,110 @@ export class PeerPigeonUI {
1768
2154
  </div>
1769
2155
  </div>
1770
2156
  `;
1771
- }).join('');
1772
- }
1773
-
1774
- updateSettings() {
1775
- // Update form values to match mesh state
1776
- const minPeersInput = document.getElementById('min-peers');
1777
- const maxPeersInput = document.getElementById('max-peers');
1778
- const autoDiscoveryToggle = document.getElementById('auto-discovery-toggle');
1779
- const evictionStrategyToggle = document.getElementById('eviction-strategy-toggle');
1780
- const xorRoutingToggle = document.getElementById('xor-routing-toggle');
1781
- const webdhtToggle = document.getElementById('webdht-toggle');
1782
-
1783
- if (minPeersInput) minPeersInput.value = this.mesh.minPeers;
1784
- if (maxPeersInput) maxPeersInput.value = this.mesh.maxPeers;
1785
- if (autoDiscoveryToggle) autoDiscoveryToggle.checked = this.mesh.autoDiscovery;
1786
- if (evictionStrategyToggle) evictionStrategyToggle.checked = this.mesh.evictionStrategy;
1787
- if (xorRoutingToggle) xorRoutingToggle.checked = this.mesh.xorRouting;
1788
-
1789
- // Update WebDHT status (read-only)
1790
- if (webdhtToggle) {
1791
- const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
1792
- webdhtToggle.checked = isDHTEnabled;
1793
-
1794
- // Update the visual styling based on status
1795
- const parent = webdhtToggle.closest('.auto-discovery-control');
1796
- if (parent) {
1797
- if (isDHTEnabled) {
1798
- parent.style.opacity = '1';
1799
- parent.title = 'WebDHT is enabled and running';
1800
- } else {
1801
- parent.style.opacity = '0.6';
1802
- parent.title = 'WebDHT is disabled (restart required to enable)';
1803
- }
1804
- }
2157
+ }).join('');
2158
+ }
2159
+
2160
+ updateSettings() {
2161
+ // Update form values to match mesh state
2162
+ const minPeersInput = document.getElementById('min-peers');
2163
+ const maxPeersInput = document.getElementById('max-peers');
2164
+ const autoDiscoveryToggle = document.getElementById('auto-discovery-toggle');
2165
+ const evictionStrategyToggle = document.getElementById('eviction-strategy-toggle');
2166
+ const xorRoutingToggle = document.getElementById('xor-routing-toggle');
2167
+ const webdhtToggle = document.getElementById('webdht-toggle');
2168
+
2169
+ if (minPeersInput) minPeersInput.value = this.mesh.minPeers;
2170
+ if (maxPeersInput) maxPeersInput.value = this.mesh.maxPeers;
2171
+ if (autoDiscoveryToggle) autoDiscoveryToggle.checked = this.mesh.autoDiscovery;
2172
+ if (evictionStrategyToggle) evictionStrategyToggle.checked = this.mesh.evictionStrategy;
2173
+ if (xorRoutingToggle) xorRoutingToggle.checked = this.mesh.xorRouting;
2174
+
2175
+ // Update WebDHT status (read-only)
2176
+ if (webdhtToggle) {
2177
+ const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
2178
+ webdhtToggle.checked = isDHTEnabled;
2179
+
2180
+ // Update the visual styling based on status
2181
+ const parent = webdhtToggle.closest('.auto-discovery-control');
2182
+ if (parent) {
2183
+ if (isDHTEnabled) {
2184
+ parent.style.opacity = '1';
2185
+ parent.title = 'WebDHT is enabled and running';
2186
+ } else {
2187
+ parent.style.opacity = '0.6';
2188
+ parent.title = 'WebDHT is disabled (restart required to enable)';
1805
2189
  }
2190
+ }
1806
2191
  }
2192
+ }
1807
2193
 
1808
- /**
2194
+ /**
1809
2195
  * Add a message to the UI message log
1810
2196
  * @param {string} sender - Message sender identifier
1811
2197
  * @param {string} content - Message content
1812
2198
  * @param {string} type - Message type ('info', 'error', 'warning', 'own', 'dm')
1813
2199
  */
1814
- addMessage(sender, content, type = 'info') {
1815
- // System messages go to the system-messages container (below connection buttons)
1816
- // Chat messages go to the messages-log container (at the bottom)
1817
- if (sender === 'System') {
1818
- this.addSystemMessage(content, type);
1819
- } else {
1820
- this.addChatMessage(sender, content, type);
1821
- }
2200
+ addMessage(sender, content, type = 'info') {
2201
+ // System messages go to the system-messages container (below connection buttons)
2202
+ // Chat messages go to the messages-log container (at the bottom)
2203
+ if (sender === 'System') {
2204
+ this.addSystemMessage(content, type);
2205
+ } else {
2206
+ this.addChatMessage(sender, content, type);
1822
2207
  }
2208
+ }
1823
2209
 
1824
- /**
2210
+ /**
1825
2211
  * Add a system message to the system messages container below connection buttons
1826
2212
  * @param {string} content - Message content
1827
2213
  * @param {string} type - Message type ('info', 'error', 'warning')
1828
2214
  */
1829
- addSystemMessage(content, type = 'info') {
1830
- const systemMessages = document.getElementById('system-messages');
1831
- if (!systemMessages) return;
1832
-
1833
- const messageElement = document.createElement('div');
1834
- messageElement.className = `system-message ${type}`;
1835
-
1836
- const timestamp = new Date().toLocaleTimeString();
1837
-
1838
- messageElement.innerHTML = `
2215
+ addSystemMessage(content, type = 'info') {
2216
+ const systemMessages = document.getElementById('system-messages');
2217
+ if (!systemMessages) return;
2218
+
2219
+ const messageElement = document.createElement('div');
2220
+ messageElement.className = `system-message ${type}`;
2221
+
2222
+ const timestamp = new Date().toLocaleTimeString();
2223
+
2224
+ messageElement.innerHTML = `
1839
2225
  <div class="system-message-header">
1840
2226
  <span class="system-message-time">${timestamp}</span>
1841
2227
  <span class="system-message-type">${type.toUpperCase()}</span>
1842
2228
  </div>
1843
2229
  <div class="system-message-content">${content}</div>
1844
2230
  `;
1845
-
1846
- systemMessages.appendChild(messageElement);
1847
- systemMessages.scrollTop = systemMessages.scrollHeight;
1848
-
1849
- // Limit message history to prevent memory issues
1850
- const messages = systemMessages.children;
1851
- if (messages.length > 50) {
1852
- systemMessages.removeChild(messages[0]);
1853
- }
2231
+
2232
+ systemMessages.appendChild(messageElement);
2233
+ systemMessages.scrollTop = systemMessages.scrollHeight;
2234
+
2235
+ // Limit message history to prevent memory issues
2236
+ const messages = systemMessages.children;
2237
+ if (messages.length > 50) {
2238
+ systemMessages.removeChild(messages[0]);
1854
2239
  }
2240
+ }
1855
2241
 
1856
- /**
2242
+ /**
1857
2243
  * Add a chat message to the messages log at the bottom
1858
2244
  * @param {string} sender - Message sender identifier
1859
2245
  * @param {string} content - Message content
1860
- * @param {string} type - Message type ('own', 'dm')
2246
+ * @param {string} type - Message type ('own', 'dm', 'encrypted')
1861
2247
  */
1862
- addChatMessage(sender, content, type = 'info') {
1863
- const messagesLog = document.getElementById('messages-log');
1864
- if (!messagesLog) return;
1865
-
1866
- const messageElement = document.createElement('div');
1867
- messageElement.className = `message-item ${type}`;
1868
-
1869
- const timestamp = new Date().toLocaleTimeString();
1870
- const senderDisplay = sender === 'You' ? 'You' : sender.substring(0, 3);
1871
-
1872
- messageElement.innerHTML = `
2248
+ addChatMessage(sender, content, type = 'info') {
2249
+ const messagesLog = document.getElementById('messages-log');
2250
+ if (!messagesLog) return;
2251
+
2252
+ const messageElement = document.createElement('div');
2253
+ // Add 'encrypted' class if message type is 'encrypted'
2254
+ const classes = `message-item ${type}`;
2255
+ messageElement.className = classes;
2256
+
2257
+ const timestamp = new Date().toLocaleTimeString();
2258
+ const senderDisplay = sender === 'You' ? 'You' : sender.substring(0, 3);
2259
+
2260
+ messageElement.innerHTML = `
1873
2261
  <div class="avatar">${senderDisplay}</div>
1874
2262
  <div class="message-body">
1875
2263
  <div class="message-header">
@@ -1878,53 +2266,199 @@ export class PeerPigeonUI {
1878
2266
  <div class="message-content">${content}</div>
1879
2267
  </div>
1880
2268
  `;
1881
-
1882
- messagesLog.appendChild(messageElement);
1883
- messagesLog.scrollTop = messagesLog.scrollHeight;
1884
-
1885
- // Limit message history to prevent memory issues
1886
- const messages = messagesLog.children;
1887
- if (messages.length > 100) {
1888
- messagesLog.removeChild(messages[0]);
1889
- }
2269
+
2270
+ messagesLog.appendChild(messageElement);
2271
+ messagesLog.scrollTop = messagesLog.scrollHeight;
2272
+
2273
+ // Limit message history to prevent memory issues
2274
+ const messages = messagesLog.children;
2275
+ if (messages.length > 100) {
2276
+ messagesLog.removeChild(messages[0]);
1890
2277
  }
2278
+ }
1891
2279
 
1892
- /**
2280
+ /**
1893
2281
  * Add an entry to the DHT log
1894
2282
  * @param {string} message - The log message
1895
2283
  */
1896
- addDHTLogEntry(message) {
1897
- const dhtLog = document.getElementById('dht-log');
1898
- if (!dhtLog) return;
1899
-
1900
- const logEntry = document.createElement('div');
1901
- logEntry.className = 'dht-log-entry';
1902
-
1903
- const timestamp = new Date().toLocaleTimeString();
1904
- logEntry.innerHTML = `
2284
+ addDHTLogEntry(message) {
2285
+ const dhtLog = document.getElementById('dht-log');
2286
+ if (!dhtLog) return;
2287
+
2288
+ const logEntry = document.createElement('div');
2289
+ logEntry.className = 'dht-log-entry';
2290
+
2291
+ const timestamp = new Date().toLocaleTimeString();
2292
+ logEntry.innerHTML = `
1905
2293
  <span class="dht-log-time">${timestamp}</span>
1906
2294
  <span class="dht-log-message">${message}</span>
1907
2295
  `;
1908
-
1909
- dhtLog.appendChild(logEntry);
1910
- dhtLog.scrollTop = dhtLog.scrollHeight;
1911
-
1912
- // Limit log entries to prevent memory issues
1913
- const entries = dhtLog.children;
1914
- if (entries.length > 100) {
1915
- dhtLog.removeChild(entries[0]);
1916
- }
2296
+
2297
+ dhtLog.appendChild(logEntry);
2298
+ dhtLog.scrollTop = dhtLog.scrollHeight;
2299
+
2300
+ // Limit log entries to prevent memory issues
2301
+ const entries = dhtLog.children;
2302
+ if (entries.length > 100) {
2303
+ dhtLog.removeChild(entries[0]);
1917
2304
  }
2305
+ }
1918
2306
 
1919
- /**
2307
+ /**
1920
2308
  * Update the DHT status display
1921
2309
  */
1922
- updateDHTStatus() {
1923
- const dhtStatusElement = document.getElementById('dht-status');
1924
- if (!dhtStatusElement) return;
2310
+ updateDHTStatus() {
2311
+ const dhtStatusElement = document.getElementById('dht-status');
2312
+ if (!dhtStatusElement) return;
1925
2313
 
1926
- const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
1927
- dhtStatusElement.textContent = isDHTEnabled ? 'Enabled' : 'Disabled';
1928
- dhtStatusElement.className = `status ${isDHTEnabled ? 'connected' : 'disconnected'}`;
2314
+ const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
2315
+ dhtStatusElement.textContent = isDHTEnabled ? 'Enabled' : 'Disabled';
2316
+ dhtStatusElement.className = `status ${isDHTEnabled ? 'connected' : 'disconnected'}`;
2317
+ }
2318
+
2319
+ // Crypto Helper Methods
2320
+ // =====================
2321
+
2322
+ /**
2323
+ * Update the crypto status display
2324
+ */
2325
+ updateCryptoStatus() {
2326
+ // Update main crypto status
2327
+ const statusElement = document.getElementById('crypto-status');
2328
+ if (statusElement) {
2329
+ const status = this.mesh.getCryptoStatus();
2330
+ statusElement.textContent = status.enabled ? 'Enabled' : 'Disabled';
2331
+ statusElement.className = `status ${status.enabled ? 'enabled' : 'disabled'}`;
2332
+ }
2333
+
2334
+ // Update public key display
2335
+ const publicKeyElement = document.getElementById('crypto-public-key');
2336
+ if (publicKeyElement) {
2337
+ const status = this.mesh.getCryptoStatus();
2338
+ if (status.enabled && status.publicKey) {
2339
+ publicKeyElement.textContent = status.publicKey.substring(0, 40) + '...';
2340
+ publicKeyElement.title = status.publicKey; // Full key in tooltip
2341
+ } else {
2342
+ publicKeyElement.textContent = 'None';
2343
+ publicKeyElement.title = '';
2344
+ }
2345
+ }
2346
+
2347
+ // Update peer keys count
2348
+ const peerCountElement = document.getElementById('crypto-peer-count');
2349
+ if (peerCountElement) {
2350
+ const status = this.mesh.getCryptoStatus();
2351
+ const count = status.peerKeys ? Object.keys(status.peerKeys).length : 0;
2352
+ peerCountElement.textContent = count.toString();
2353
+ }
2354
+
2355
+ // Update performance statistics
2356
+ this.updateCryptoStats();
2357
+ }
2358
+
2359
+ /**
2360
+ * Update crypto performance statistics
2361
+ */
2362
+ updateCryptoStats() {
2363
+ const status = this.mesh.getCryptoStatus();
2364
+ if (!status.performance) return;
2365
+
2366
+ const stats = status.performance;
2367
+
2368
+ // Update stat elements
2369
+ const updateStat = (id, value) => {
2370
+ const element = document.getElementById(id);
2371
+ if (element) element.textContent = value.toString();
2372
+ };
2373
+
2374
+ updateStat('crypto-stats-encrypted', stats.messagesEncrypted || 0);
2375
+ updateStat('crypto-stats-decrypted', stats.messagesDecrypted || 0);
2376
+ updateStat('crypto-stats-encrypt-time', `${(stats.avgEncryptTime || 0).toFixed(2)}ms`);
2377
+ updateStat('crypto-stats-decrypt-time', `${(stats.avgDecryptTime || 0).toFixed(2)}ms`);
2378
+ updateStat('crypto-stats-key-exchanges', stats.keyExchanges || 0);
2379
+ }
2380
+
2381
+ /**
2382
+ * Add a crypto test result to the test log
2383
+ */
2384
+ addCryptoTestResult(message, type = 'info') {
2385
+ const testLog = document.getElementById('crypto-test-log');
2386
+ if (!testLog) return;
2387
+
2388
+ // Remove empty state message
2389
+ const emptyState = testLog.querySelector('.empty-state');
2390
+ if (emptyState) {
2391
+ emptyState.remove();
2392
+ }
2393
+
2394
+ const logEntry = document.createElement('div');
2395
+ logEntry.className = `test-result ${type}`;
2396
+
2397
+ const timestamp = new Date().toLocaleTimeString();
2398
+ logEntry.innerHTML = `
2399
+ <span class="test-time">${timestamp}</span>
2400
+ <span class="test-message">${message}</span>
2401
+ `;
2402
+
2403
+ testLog.appendChild(logEntry);
2404
+ testLog.scrollTop = testLog.scrollHeight;
2405
+
2406
+ // Limit log entries to prevent memory issues
2407
+ const entries = testLog.querySelectorAll('.test-result');
2408
+ if (entries.length > 50) {
2409
+ entries[0].remove();
2410
+ }
2411
+ }
2412
+
2413
+ /**
2414
+ * Clear all crypto test results
2415
+ */
2416
+ clearCryptoTestResults() {
2417
+ const testLog = document.getElementById('crypto-test-log');
2418
+ if (!testLog) return;
2419
+
2420
+ testLog.innerHTML = '<p class="empty-state">No tests run yet</p>';
2421
+ }
2422
+
2423
+ /**
2424
+ * Update the group select dropdown
2425
+ */
2426
+ updateGroupSelect() {
2427
+ const groupSelect = document.getElementById('crypto-group-select');
2428
+ const groupsList = document.getElementById('crypto-groups-list');
2429
+ if (!groupSelect || !groupsList) return;
2430
+
2431
+ const status = this.mesh.getCryptoStatus();
2432
+ const groups = status.groups || {};
2433
+
2434
+ // Clear existing options (except placeholder)
2435
+ const placeholder = groupSelect.querySelector('option[value=""]');
2436
+ groupSelect.innerHTML = '';
2437
+ if (placeholder) groupSelect.appendChild(placeholder);
2438
+
2439
+ // Add group options
2440
+ Object.keys(groups).forEach(groupId => {
2441
+ const option = document.createElement('option');
2442
+ option.value = groupId;
2443
+ option.textContent = groupId;
2444
+ groupSelect.appendChild(option);
2445
+ });
2446
+
2447
+ // Update groups list display
2448
+ const groupCount = Object.keys(groups).length;
2449
+ if (groupCount === 0) {
2450
+ groupsList.innerHTML = '<h4>Active Groups:</h4><div class="empty-state">No groups created</div>';
2451
+ } else {
2452
+ let html = '<h4>Active Groups:</h4>';
2453
+ Object.entries(groups).forEach(([groupId, groupInfo]) => {
2454
+ html += `
2455
+ <div class="group-item">
2456
+ <strong>${groupId}</strong>
2457
+ <small>Created: ${new Date(groupInfo.created).toLocaleString()}</small>
2458
+ </div>
2459
+ `;
2460
+ });
2461
+ groupsList.innerHTML = html;
1929
2462
  }
1930
- }
2463
+ }
2464
+ }