peerpigeon 0.1.1 → 1.0.0

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.
Files changed (70) hide show
  1. package/README.md +141 -1365
  2. package/cli.js +1382 -0
  3. package/dist/peerpigeon-browser.js +12290 -0
  4. package/dist/peerpigeon-browser.js.map +7 -0
  5. package/docs/API_DOCUMENTATION.md +1945 -0
  6. package/docs/BOOTSTRAP_HUBS.md +319 -0
  7. package/docs/CLI_README.md +371 -0
  8. package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
  9. package/docs/HUB_QUICK_REF.md +107 -0
  10. package/docs/HUB_SCRIPTS.md +331 -0
  11. package/docs/HUB_SYSTEM.md +552 -0
  12. package/docs/MIGRATION_COMPLETE.md +93 -0
  13. package/docs/NETWORK_NAMESPACES.md +212 -0
  14. package/docs/README.md +107 -0
  15. package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
  16. package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
  17. package/examples/bootstrap-hub-example.js +292 -0
  18. package/examples/browser/README.md +278 -0
  19. package/examples/browser/app.js +2426 -49
  20. package/examples/browser/index.html +481 -630
  21. package/examples/browser/minimal/README.md +55 -0
  22. package/examples/browser/minimal/index.html +75 -0
  23. package/examples/browser/minimal/minimal.js +234 -0
  24. package/examples/browser/styles.css +687 -1425
  25. package/examples/browser/test-bundle.html +35 -0
  26. package/examples/browser-2/index.html +30 -0
  27. package/examples/browser-2/package.json +21 -0
  28. package/examples/browser-2/src/App-simple.vue +21 -0
  29. package/examples/browser-2/src/App.vue +420 -0
  30. package/examples/browser-2/src/components/CryptoView.vue +1661 -0
  31. package/examples/browser-2/src/components/DHTView.vue +1281 -0
  32. package/examples/browser-2/src/components/DebugView.vue +1773 -0
  33. package/examples/browser-2/src/components/MediaView.vue +1048 -0
  34. package/examples/browser-2/src/components/MessagingView.vue +775 -0
  35. package/examples/browser-2/src/components/NetworkView.vue +930 -0
  36. package/examples/browser-2/src/components/StorageView.vue +1376 -0
  37. package/examples/browser-2/src/main.js +5 -0
  38. package/examples/browser-2/src/stores/peerpigeon.js +895 -0
  39. package/examples/browser-2/vite.config.js +6 -0
  40. package/examples/hub-example.js +186 -0
  41. package/examples/multi-hub-test.js +186 -0
  42. package/examples/node/README.md +2 -2
  43. package/examples/selective-streaming-demo.html +698 -0
  44. package/examples/standard-events-demo.js +126 -0
  45. package/package.json +33 -16
  46. package/server/index.js +1032 -98
  47. package/server/start.js +49 -0
  48. package/src/ConnectionManager.js +239 -225
  49. package/src/CryptoManager.js +147 -18
  50. package/src/DebugLogger.js +0 -7
  51. package/src/DistributedStorageManager.js +224 -205
  52. package/src/EnvironmentDetector.js +109 -2
  53. package/src/EventEmitter.js +79 -1
  54. package/src/EvictionManager.js +10 -9
  55. package/src/GossipManager.js +163 -11
  56. package/src/PeerConnection.js +333 -310
  57. package/src/PeerPigeonMesh.js +577 -135
  58. package/src/SignalingClient.js +14 -243
  59. package/src/SignalingHandler.js +31 -10
  60. package/src/StorageManager.js +0 -39
  61. package/src/WebDHT-Simple.js +389 -0
  62. package/src/WebDHT.js +363 -1165
  63. package/src/browser-entry.js +40 -0
  64. package/examples/browser/assets/images/favicon.png +0 -0
  65. package/examples/browser/assets/images/pigeon.png +0 -0
  66. package/examples/browser/crypto-test.html +0 -427
  67. package/examples/browser/ui-old.js +0 -1926
  68. package/examples/browser/ui.js +0 -3391
  69. package/websocket-server/README.md +0 -247
  70. package/websocket-server/server.js +0 -391
@@ -1,3391 +0,0 @@
1
- // Updated: 2025-07-04 - Fixed getConnectionStatus method name
2
- export class PeerPigeonUI {
3
- constructor(mesh) {
4
- this.mesh = mesh;
5
- this.lastCleanupTime = 0; // Track when we last did cleanup
6
- this.setupEventListeners();
7
- this.bindDOMEvents();
8
- this.initializeMedia();
9
- }
10
-
11
- setupEventListeners() {
12
- this.mesh.addEventListener('statusChanged', (data) => {
13
- this.handleStatusChange(data);
14
- });
15
-
16
- this.mesh.addEventListener('peerDiscovered', (_data) => {
17
- this.updateDiscoveredPeers();
18
- });
19
-
20
- this.mesh.addEventListener('peerConnected', (_data) => {
21
- this.updateUI();
22
- this.updateDiscoveredPeers();
23
- });
24
-
25
- this.mesh.addEventListener('peerDisconnected', (data) => {
26
- this.addMessage('System', `Peer ${data.peerId.substring(0, 8)}... disconnected (${data.reason})`);
27
- this.updateUI();
28
- this.updateDiscoveredPeers();
29
- });
30
-
31
- this.mesh.addEventListener('messageReceived', (data) => {
32
- // Only show messages from other peers, not self
33
- if (data.from !== this.mesh.peerId) {
34
- if (data.direct) {
35
- this.addMessage(`${data.from.substring(0, 8)}...`, `(DM) ${data.content}`, 'dm');
36
- } else {
37
- this.addMessage(`${data.from.substring(0, 8)}...`, data.content);
38
- }
39
- }
40
- });
41
-
42
- this.mesh.addEventListener('peerEvicted', (_data) => {
43
- this.updateUI();
44
- this.updateDiscoveredPeers();
45
- });
46
-
47
- this.mesh.addEventListener('peersUpdated', () => {
48
- this.updateDiscoveredPeers();
49
- });
50
-
51
- this.mesh.addEventListener('connectionStats', (_stats) => {
52
- // Handle connection stats if needed
53
- });
54
-
55
- // DHT event listeners
56
- this.mesh.addEventListener('dhtValueChanged', (data) => {
57
- const { key, newValue, timestamp } = data;
58
- this.addDHTLogEntry(`🔔 Value Changed: ${key} = ${JSON.stringify(newValue)} (timestamp: ${timestamp})`);
59
- });
60
-
61
- // Media event listeners
62
- this.mesh.addEventListener('localStreamStarted', (data) => {
63
- this.handleLocalStreamStarted(data);
64
- });
65
-
66
- this.mesh.addEventListener('localStreamStopped', () => {
67
- this.handleLocalStreamStopped();
68
- });
69
-
70
- this.mesh.addEventListener('mediaError', (data) => {
71
- this.addMessage('System', `Media error: ${data.error.message}`, 'error');
72
- });
73
-
74
- // Listen for remote streams
75
- this.mesh.addEventListener('remoteStream', (data) => {
76
- this.handleRemoteStream(data);
77
- });
78
-
79
- // 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
- // Storage controls
221
- this.setupStorageControls();
222
-
223
- // Crypto controls
224
- this.setupCryptoControls();
225
-
226
- // Collapsible sections
227
- this.setupCollapsibleSections();
228
-
229
- // Media controls
230
- this.setupMediaControls();
231
- }
232
-
233
- setupDHTControls() {
234
- // DHT input fields and controls
235
- const dhtKey = document.getElementById('dht-key');
236
- const dhtValue = document.getElementById('dht-value');
237
- const dhtGetKey = document.getElementById('dht-get-key'); // Separate key field for retrieval
238
- const dhtSubscribeKey = document.getElementById('dht-subscribe-key'); // Separate key field for subscription
239
- const dhtPutBtn = document.getElementById('dht-put-btn');
240
- const dhtUpdateBtn = document.getElementById('dht-update-btn');
241
- const dhtGetBtn = document.getElementById('dht-get-btn');
242
- const dhtSubscribeBtn = document.getElementById('dht-subscribe-btn');
243
- const dhtUnsubscribeBtn = document.getElementById('dht-unsubscribe-btn');
244
- const dhtEnableTtl = document.getElementById('dht-enable-ttl');
245
- const dhtTtlGroup = document.getElementById('dht-ttl-group');
246
- const dhtTtl = document.getElementById('dht-ttl');
247
-
248
- // Debug: Check if elements are found
249
- console.log('DHT Controls setup - Elements found:', {
250
- dhtKey: !!dhtKey,
251
- dhtValue: !!dhtValue,
252
- dhtGetKey: !!dhtGetKey,
253
- dhtSubscribeKey: !!dhtSubscribeKey,
254
- dhtPutBtn: !!dhtPutBtn,
255
- dhtUpdateBtn: !!dhtUpdateBtn,
256
- dhtGetBtn: !!dhtGetBtn,
257
- dhtSubscribeBtn: !!dhtSubscribeBtn,
258
- dhtUnsubscribeBtn: !!dhtUnsubscribeBtn
259
- });
260
-
261
- if (!dhtKey) {
262
- console.error('DHT key input element not found!');
263
- this.addDHTLogEntry('❌ Error: DHT key input field not found in DOM');
264
- }
265
-
266
- if (!dhtValue) {
267
- console.error('DHT value input element not found!');
268
- this.addDHTLogEntry('❌ Error: DHT value input field not found in DOM');
269
- }
270
-
271
- if (!dhtGetKey) {
272
- console.error('DHT get-key input element not found!');
273
- this.addDHTLogEntry('❌ Error: DHT get-key input field not found in DOM');
274
- }
275
-
276
- // Toggle TTL input visibility
277
- if (dhtEnableTtl && dhtTtlGroup) {
278
- dhtEnableTtl.addEventListener('change', (e) => {
279
- dhtTtlGroup.style.display = e.target.checked ? 'block' : 'none';
280
- });
281
- }
282
-
283
- // Store in DHT
284
- if (dhtPutBtn) {
285
- dhtPutBtn.addEventListener('click', async () => {
286
- const key = dhtKey?.value?.trim();
287
- const value = dhtValue?.value?.trim();
288
-
289
- // Debug logging
290
- console.log('DHT PUT - Elements found:', {
291
- dhtKey: !!dhtKey,
292
- dhtValue: !!dhtValue,
293
- keyValue: key,
294
- valueValue: value
295
- });
296
-
297
- if (!key || !value) {
298
- this.addDHTLogEntry('❌ Error: Both key and value are required');
299
- this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
300
- return;
301
- }
302
-
303
- if (!this.mesh.isDHTEnabled()) {
304
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
305
- return;
306
- }
307
-
308
- try {
309
- let parsedValue;
310
- try {
311
- parsedValue = JSON.parse(value);
312
- } catch {
313
- parsedValue = value; // Use as string if not valid JSON
314
- }
315
-
316
- const options = {};
317
- if (dhtEnableTtl?.checked && dhtTtl?.value) {
318
- options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
319
- }
320
-
321
- const success = await this.mesh.dhtPut(key, parsedValue, options);
322
- if (success) {
323
- this.addDHTLogEntry(`✅ Stored: ${key} = ${JSON.stringify(parsedValue)}`);
324
- if (options.ttl) {
325
- this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
326
- }
327
- this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
328
-
329
- // Auto-subscribe to the key we just stored (essential for original storing peers)
330
- try {
331
- await this.mesh.dhtSubscribe(key);
332
- this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
333
- this.addDHTLogEntry(' 📡 Will receive and relay all future updates for this key');
334
- } catch (subscribeError) {
335
- this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
336
- }
337
- } else {
338
- this.addDHTLogEntry(`❌ Failed to store: ${key}`);
339
- }
340
- } catch (error) {
341
- this.addDHTLogEntry(`❌ Error storing ${key}: ${error.message}`);
342
- }
343
- });
344
- }
345
-
346
- // Update in DHT
347
- if (dhtUpdateBtn) {
348
- dhtUpdateBtn.addEventListener('click', async () => {
349
- const key = dhtKey?.value?.trim();
350
- const value = dhtValue?.value?.trim();
351
-
352
- // Debug logging
353
- console.log('DHT UPDATE - Elements found:', {
354
- dhtKey: !!dhtKey,
355
- dhtValue: !!dhtValue,
356
- keyValue: key,
357
- valueValue: value
358
- });
359
-
360
- if (!key || !value) {
361
- this.addDHTLogEntry('❌ Error: Both key and value are required');
362
- this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
363
- return;
364
- }
365
-
366
- if (!this.mesh.isDHTEnabled()) {
367
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
368
- return;
369
- }
370
-
371
- try {
372
- let parsedValue;
373
- try {
374
- parsedValue = JSON.parse(value);
375
- } catch {
376
- parsedValue = value; // Use as string if not valid JSON
377
- }
378
-
379
- const options = {};
380
- if (dhtEnableTtl?.checked && dhtTtl?.value) {
381
- options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
382
- }
383
-
384
- const success = await this.mesh.dhtUpdate(key, parsedValue, options);
385
- if (success) {
386
- this.addDHTLogEntry(`🔄 Updated: ${key} = ${JSON.stringify(parsedValue)}`);
387
- if (options.ttl) {
388
- this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
389
- }
390
- this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
391
-
392
- // Auto-subscribe to the key we just updated (essential for original storing peers)
393
- try {
394
- await this.mesh.dhtSubscribe(key);
395
- this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
396
- this.addDHTLogEntry(' 📡 Will receive and relay all future updates for this key');
397
- } catch (subscribeError) {
398
- this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
399
- }
400
- } else {
401
- this.addDHTLogEntry(`❌ Failed to update: ${key}`);
402
- }
403
- } catch (error) {
404
- this.addDHTLogEntry(`❌ Error updating ${key}: ${error.message}`);
405
- }
406
- });
407
- }
408
-
409
- // Get from DHT
410
- if (dhtGetBtn) {
411
- dhtGetBtn.addEventListener('click', async () => {
412
- const key = dhtGetKey?.value?.trim(); // Fixed: Use dhtGetKey instead of dhtKey
413
-
414
- // Debug logging
415
- console.log('DHT GET - Elements found:', {
416
- dhtGetKey: !!dhtGetKey,
417
- keyValue: key
418
- });
419
-
420
- if (!key) {
421
- this.addDHTLogEntry('❌ Error: Key is required');
422
- this.addDHTLogEntry(` Debug: key="${key}"`);
423
- return;
424
- }
425
-
426
- if (!this.mesh.isDHTEnabled()) {
427
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
428
- return;
429
- }
430
-
431
- try {
432
- this.addDHTLogEntry(`🔍 Fetching from ORIGINAL STORING PEERS: ${key}`);
433
- this.addDHTLogEntry(' 📡 Bypassing local cache to ensure fresh data');
434
-
435
- // Force fresh retrieval from original storing peers
436
- const value = await this.mesh.dhtGet(key, { forceRefresh: true });
437
- if (value !== null) {
438
- this.addDHTLogEntry(`📥 Retrieved from original peers: ${key} = ${JSON.stringify(value)}`);
439
- this.addDHTLogEntry(' ✅ Data is FRESH from authoritative source');
440
- if (dhtValue) {
441
- dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
442
- }
443
-
444
- // Auto-subscribe to the key we just retrieved for future updates
445
- try {
446
- await this.mesh.dhtSubscribe(key);
447
- this.addDHTLogEntry(`🔔 Auto-subscribed for future updates: ${key}`);
448
- this.addDHTLogEntry(' 📡 Will receive notifications when original peers update this key');
449
- } catch (subscribeError) {
450
- this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
451
- }
452
- } else {
453
- this.addDHTLogEntry(`❌ Not found on original storing peers: ${key}`);
454
- this.addDHTLogEntry(' 💡 Key may not exist or all original storing peers are offline');
455
- }
456
- } catch (error) {
457
- this.addDHTLogEntry(`❌ Error retrieving ${key}: ${error.message}`);
458
- }
459
- });
460
- }
461
-
462
- // Subscribe to DHT key
463
- if (dhtSubscribeBtn) {
464
- dhtSubscribeBtn.addEventListener('click', async () => {
465
- // Use the dedicated subscription key field
466
- const key = dhtSubscribeKey?.value?.trim();
467
-
468
- if (!key) {
469
- this.addDHTLogEntry('❌ Error: Key is required for subscription');
470
- return;
471
- }
472
-
473
- if (!this.mesh.isDHTEnabled()) {
474
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
475
- return;
476
- }
477
-
478
- try {
479
- this.addDHTLogEntry(`🔔 Explicitly subscribing to key: ${key}`);
480
- this.addDHTLogEntry(' 📡 Will receive notifications when original storing peers update this key');
481
-
482
- const value = await this.mesh.dhtSubscribe(key);
483
- this.addDHTLogEntry(`✅ Subscribed to: ${key}`);
484
- if (value !== null) {
485
- this.addDHTLogEntry(` Current value from original storing peers: ${JSON.stringify(value)}`);
486
- } else {
487
- this.addDHTLogEntry(' No current value found on original storing peers');
488
- }
489
-
490
- // Clear the subscription key field after successful subscription
491
- if (dhtSubscribeKey) {
492
- dhtSubscribeKey.value = '';
493
- }
494
- } catch (error) {
495
- this.addDHTLogEntry(`❌ Error subscribing to ${key}: ${error.message}`);
496
- }
497
- });
498
- }
499
-
500
- // Unsubscribe from DHT key
501
- if (dhtUnsubscribeBtn) {
502
- dhtUnsubscribeBtn.addEventListener('click', async () => {
503
- // Use the dedicated subscription key field
504
- const key = dhtSubscribeKey?.value?.trim();
505
-
506
- if (!key) {
507
- this.addDHTLogEntry('❌ Error: Key is required for unsubscription');
508
- return;
509
- }
510
-
511
- if (!this.mesh.isDHTEnabled()) {
512
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
513
- return;
514
- }
515
-
516
- try {
517
- await this.mesh.dhtUnsubscribe(key);
518
- this.addDHTLogEntry(`🔕 Unsubscribed from: ${key}`);
519
-
520
- // Clear the subscription key field after successful unsubscription
521
- if (dhtSubscribeKey) {
522
- dhtSubscribeKey.value = '';
523
- }
524
- } catch (error) {
525
- this.addDHTLogEntry(`❌ Error unsubscribing from ${key}: ${error.message}`);
526
- }
527
- });
528
- }
529
- }
530
-
531
- setupStorageControls() {
532
- // Ensure storage section starts collapsed with robust hiding
533
- const storageSection = document.querySelector('.storage');
534
- const storageToggle = document.getElementById('storage-toggle');
535
- const storageContent = document.getElementById('storage-content');
536
-
537
- if (storageSection && storageToggle && storageContent) {
538
- // Force initial collapsed state with multiple approaches
539
- storageSection.setAttribute('aria-expanded', 'false');
540
- storageToggle.setAttribute('aria-expanded', 'false');
541
-
542
- // Use multiple ways to hide the content
543
- storageContent.style.display = 'none';
544
- storageContent.style.visibility = 'hidden';
545
- storageContent.style.maxHeight = '0';
546
- storageContent.style.overflow = 'hidden';
547
- storageContent.classList.add('collapsed');
548
-
549
- // Ensure the toggle button shows collapsed state
550
- if (storageToggle.textContent && !storageToggle.textContent.includes('▶')) {
551
- storageToggle.textContent = storageToggle.textContent.replace('▼', '▶');
552
- }
553
- }
554
-
555
- // Enable/Disable Storage
556
- const storageEnableBtn = document.getElementById('storage-enable-btn');
557
- const storageDisableBtn = document.getElementById('storage-disable-btn');
558
- const storageClearBtn = document.getElementById('storage-clear-btn');
559
-
560
- if (storageEnableBtn) {
561
- storageEnableBtn.addEventListener('click', async () => {
562
- try {
563
- if (!this.mesh.distributedStorage) {
564
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
565
- return;
566
- }
567
-
568
- await this.mesh.distributedStorage.enable();
569
- this.addStorageLogEntry('✅ Distributed storage enabled');
570
- this.updateStorageStatus();
571
- } catch (error) {
572
- this.addStorageLogEntry(`❌ Error enabling storage: ${error.message}`);
573
- }
574
- });
575
- }
576
-
577
- if (storageDisableBtn) {
578
- storageDisableBtn.addEventListener('click', async () => {
579
- try {
580
- if (!this.mesh.distributedStorage) {
581
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
582
- return;
583
- }
584
-
585
- await this.mesh.distributedStorage.disable();
586
- this.addStorageLogEntry('⚠️ Distributed storage disabled');
587
- this.updateStorageStatus();
588
- } catch (error) {
589
- this.addStorageLogEntry(`❌ Error disabling storage: ${error.message}`);
590
- }
591
- });
592
- }
593
-
594
- if (storageClearBtn) {
595
- storageClearBtn.addEventListener('click', async () => {
596
- if (!confirm('Are you sure you want to clear all stored data? This cannot be undone.')) {
597
- return;
598
- }
599
-
600
- try {
601
- if (!this.mesh.distributedStorage) {
602
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
603
- return;
604
- }
605
-
606
- await this.mesh.distributedStorage.clear();
607
- this.addStorageLogEntry('🗑️ All stored data cleared');
608
- this.updateStorageStatus();
609
- } catch (error) {
610
- this.addStorageLogEntry(`❌ Error clearing storage: ${error.message}`);
611
- }
612
- });
613
- }
614
-
615
- // Store Data
616
- const storageStoreBtn = document.getElementById('storage-store-btn');
617
- const storageUpdateBtn = document.getElementById('storage-update-btn');
618
-
619
- if (storageStoreBtn) {
620
- storageStoreBtn.addEventListener('click', async () => {
621
- await this.handleStorageStore(false);
622
- });
623
- }
624
-
625
- if (storageUpdateBtn) {
626
- storageUpdateBtn.addEventListener('click', async () => {
627
- await this.handleStorageStore(true);
628
- });
629
- }
630
-
631
- // Retrieve Data
632
- const storageGetBtn = document.getElementById('storage-get-btn');
633
- const storageDeleteBtn = document.getElementById('storage-delete-btn');
634
-
635
- if (storageGetBtn) {
636
- storageGetBtn.addEventListener('click', async () => {
637
- const key = document.getElementById('storage-get-key')?.value?.trim();
638
-
639
- if (!key) {
640
- this.addStorageLogEntry('❌ Error: Key is required');
641
- return;
642
- }
643
-
644
- try {
645
- if (!this.mesh.distributedStorage) {
646
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
647
- return;
648
- }
649
-
650
- const result = await this.mesh.distributedStorage.retrieve(key);
651
- if (result !== null) {
652
- this.addStorageLogEntry(`📋 Retrieved: ${key} = ${JSON.stringify(result)}`);
653
-
654
- // Get key info for metadata display
655
- try {
656
- const keyInfo = await this.mesh.distributedStorage.getKeyInfo(key);
657
- if (keyInfo) {
658
- this.addStorageLogEntry(` Metadata: public=${keyInfo.isPublic}, immutable=${keyInfo.isImmutable}, owner=${keyInfo.owner?.substring(0, 8)}...`);
659
- this.addStorageLogEntry(` Created: ${new Date(keyInfo.createdAt).toLocaleString()}`);
660
- }
661
- } catch (metaError) {
662
- // Metadata display is optional, don't fail the retrieval
663
- console.warn('Could not get metadata for display:', metaError);
664
- }
665
- } else {
666
- this.addStorageLogEntry(`❌ Key not found or access denied: ${key}`);
667
- }
668
- } catch (error) {
669
- this.addStorageLogEntry(`❌ Error retrieving ${key}: ${error.message}`);
670
- }
671
- });
672
- }
673
-
674
- if (storageDeleteBtn) {
675
- storageDeleteBtn.addEventListener('click', async () => {
676
- const key = document.getElementById('storage-get-key')?.value?.trim();
677
-
678
- if (!key) {
679
- this.addStorageLogEntry('❌ Error: Key is required');
680
- return;
681
- }
682
-
683
- if (!confirm(`Are you sure you want to delete "${key}"? This cannot be undone.`)) {
684
- return;
685
- }
686
-
687
- try {
688
- if (!this.mesh.distributedStorage) {
689
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
690
- return;
691
- }
692
-
693
- const success = await this.mesh.distributedStorage.delete(key);
694
- if (success) {
695
- this.addStorageLogEntry(`🗑️ Deleted: ${key}`);
696
- this.updateStorageStatus();
697
- } else {
698
- this.addStorageLogEntry(`❌ Failed to delete: ${key}`);
699
- }
700
- } catch (error) {
701
- this.addStorageLogEntry(`❌ Error deleting ${key}: ${error.message}`);
702
- }
703
- });
704
- }
705
-
706
- // Access Control
707
- const storageGrantAccessBtn = document.getElementById('storage-grant-access-btn');
708
- const storageRevokeAccessBtn = document.getElementById('storage-revoke-access-btn');
709
-
710
- if (storageGrantAccessBtn) {
711
- storageGrantAccessBtn.addEventListener('click', async () => {
712
- const key = document.getElementById('storage-access-key')?.value?.trim();
713
- const peerId = document.getElementById('storage-access-peer')?.value?.trim();
714
- const level = document.getElementById('storage-access-level')?.value;
715
-
716
- if (!key || !peerId) {
717
- this.addStorageLogEntry('❌ Error: Key and peer ID are required');
718
- return;
719
- }
720
-
721
- try {
722
- if (!this.mesh.distributedStorage) {
723
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
724
- return;
725
- }
726
-
727
- const success = await this.mesh.distributedStorage.grantAccess(key, peerId, level);
728
- if (success) {
729
- this.addStorageLogEntry(`✅ Granted ${level} access to ${peerId.substring(0, 8)}... for key: ${key}`);
730
- } else {
731
- this.addStorageLogEntry('❌ Failed to grant access');
732
- }
733
- } catch (error) {
734
- this.addStorageLogEntry(`❌ Error granting access: ${error.message}`);
735
- }
736
- });
737
- }
738
-
739
- if (storageRevokeAccessBtn) {
740
- storageRevokeAccessBtn.addEventListener('click', async () => {
741
- const key = document.getElementById('storage-revoke-key')?.value?.trim();
742
- const peerId = document.getElementById('storage-revoke-peer')?.value?.trim();
743
-
744
- if (!key || !peerId) {
745
- this.addStorageLogEntry('❌ Error: Key and peer ID are required');
746
- return;
747
- }
748
-
749
- try {
750
- if (!this.mesh.distributedStorage) {
751
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
752
- return;
753
- }
754
-
755
- const success = await this.mesh.distributedStorage.revokeAccess(key, peerId);
756
- if (success) {
757
- this.addStorageLogEntry(`✅ Revoked access from ${peerId.substring(0, 8)}... for key: ${key}`);
758
- } else {
759
- this.addStorageLogEntry('❌ Failed to revoke access');
760
- }
761
- } catch (error) {
762
- this.addStorageLogEntry(`❌ Error revoking access: ${error.message}`);
763
- }
764
- });
765
- }
766
-
767
- // Bulk Operations
768
- const storageListBtn = document.getElementById('storage-list-btn');
769
- const storageBulkDeleteBtn = document.getElementById('storage-bulk-delete-btn');
770
-
771
- if (storageListBtn) {
772
- storageListBtn.addEventListener('click', async () => {
773
- const prefix = document.getElementById('storage-prefix')?.value?.trim() || '';
774
-
775
- try {
776
- if (!this.mesh.distributedStorage) {
777
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
778
- return;
779
- }
780
-
781
- const keys = await this.mesh.distributedStorage.listKeys(prefix);
782
- if (keys.length > 0) {
783
- this.addStorageLogEntry(`📋 Found ${keys.length} keys with prefix "${prefix}":`);
784
- keys.forEach(key => {
785
- this.addStorageLogEntry(` • ${key}`);
786
- });
787
- } else {
788
- this.addStorageLogEntry(`❌ No keys found with prefix "${prefix}"`);
789
- }
790
- } catch (error) {
791
- this.addStorageLogEntry(`❌ Error listing keys: ${error.message}`);
792
- }
793
- });
794
- }
795
-
796
- if (storageBulkDeleteBtn) {
797
- storageBulkDeleteBtn.addEventListener('click', async () => {
798
- const prefix = document.getElementById('storage-prefix')?.value?.trim();
799
-
800
- if (!prefix) {
801
- this.addStorageLogEntry('❌ Error: Prefix is required for bulk delete');
802
- return;
803
- }
804
-
805
- if (!confirm(`Are you sure you want to delete all keys with prefix "${prefix}"? This cannot be undone.`)) {
806
- return;
807
- }
808
-
809
- try {
810
- if (!this.mesh.distributedStorage) {
811
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
812
- return;
813
- }
814
-
815
- const count = await this.mesh.distributedStorage.bulkDelete(prefix);
816
- this.addStorageLogEntry(`🗑️ Bulk deleted ${count} keys with prefix "${prefix}"`);
817
- this.updateStorageStatus();
818
- } catch (error) {
819
- this.addStorageLogEntry(`❌ Error bulk deleting: ${error.message}`);
820
- }
821
- });
822
- }
823
-
824
- // Search
825
- const storageSearchBtn = document.getElementById('storage-search-btn');
826
-
827
- if (storageSearchBtn) {
828
- storageSearchBtn.addEventListener('click', async () => {
829
- const query = document.getElementById('storage-search-query')?.value?.trim();
830
- const type = document.getElementById('storage-search-type')?.value || 'key';
831
-
832
- if (!query) {
833
- this.addStorageLogEntry('❌ Error: Search query is required');
834
- return;
835
- }
836
-
837
- try {
838
- if (!this.mesh.distributedStorage) {
839
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
840
- return;
841
- }
842
-
843
- const results = await this.mesh.distributedStorage.search(query, type);
844
- if (results.length > 0) {
845
- this.addStorageLogEntry(`🔍 Found ${results.length} results for "${query}" in ${type}:`);
846
- results.forEach(result => {
847
- this.addStorageLogEntry(` • ${result.key}: ${JSON.stringify(result.value).substring(0, 100)}...`);
848
- });
849
- } else {
850
- this.addStorageLogEntry(`❌ No results found for "${query}" in ${type}`);
851
- }
852
- } catch (error) {
853
- this.addStorageLogEntry(`❌ Error searching: ${error.message}`);
854
- }
855
- });
856
- }
857
-
858
- // Backup/Restore
859
- const storageBackupBtn = document.getElementById('storage-backup-btn');
860
- const storageRestoreBtn = document.getElementById('storage-restore-btn');
861
- const storageRestoreFile = document.getElementById('storage-restore-file');
862
-
863
- if (storageBackupBtn) {
864
- storageBackupBtn.addEventListener('click', async () => {
865
- try {
866
- if (!this.mesh.distributedStorage) {
867
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
868
- return;
869
- }
870
-
871
- const backup = await this.mesh.distributedStorage.backup();
872
- const blob = new Blob([JSON.stringify(backup, null, 2)], { type: 'application/json' });
873
- const url = URL.createObjectURL(blob);
874
-
875
- const a = document.createElement('a');
876
- a.href = url;
877
- a.download = `peerpigeon-storage-backup-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
878
- a.click();
879
-
880
- URL.revokeObjectURL(url);
881
- this.addStorageLogEntry(`💾 Backup created with ${backup.items.length} items`);
882
- } catch (error) {
883
- this.addStorageLogEntry(`❌ Error creating backup: ${error.message}`);
884
- }
885
- });
886
- }
887
-
888
- if (storageRestoreBtn) {
889
- storageRestoreBtn.addEventListener('click', () => {
890
- storageRestoreFile?.click();
891
- });
892
- }
893
-
894
- if (storageRestoreFile) {
895
- storageRestoreFile.addEventListener('change', async (e) => {
896
- const file = e.target.files[0];
897
- if (!file) return;
898
-
899
- try {
900
- const text = await file.text();
901
- const backup = JSON.parse(text);
902
-
903
- if (!this.mesh.distributedStorage) {
904
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
905
- return;
906
- }
907
-
908
- const result = await this.mesh.distributedStorage.restore(backup);
909
- this.addStorageLogEntry(`📥 Restored ${result.restored} items (${result.failed} failed)`);
910
- this.updateStorageStatus();
911
- } catch (error) {
912
- this.addStorageLogEntry(`❌ Error restoring backup: ${error.message}`);
913
- }
914
-
915
- // Clear the file input
916
- e.target.value = '';
917
- });
918
- }
919
-
920
- // Setup Lexical Storage Interface
921
- this.setupLexicalStorageControls();
922
- }
923
-
924
- setupLexicalStorageControls() {
925
- // Chain Operations
926
- const lexicalPutBtn = document.getElementById('lexical-put-btn');
927
- const lexicalGetBtn = document.getElementById('lexical-get-btn');
928
- const lexicalValBtn = document.getElementById('lexical-val-btn');
929
- const lexicalUpdateBtn = document.getElementById('lexical-update-btn');
930
- const lexicalDeleteBtn = document.getElementById('lexical-delete-btn');
931
-
932
- // Set Operations
933
- const lexicalSetBtn = document.getElementById('lexical-set-btn');
934
- const lexicalMapBtn = document.getElementById('lexical-map-btn');
935
-
936
- // Property Access
937
- const lexicalProxySetBtn = document.getElementById('lexical-proxy-set-btn');
938
- const lexicalProxyGetBtn = document.getElementById('lexical-proxy-get-btn');
939
-
940
- // Utility Operations
941
- const lexicalExistsBtn = document.getElementById('lexical-exists-btn');
942
- const lexicalKeysBtn = document.getElementById('lexical-keys-btn');
943
- const lexicalPathBtn = document.getElementById('lexical-path-btn');
944
-
945
- // Chain Operations Event Handlers
946
- if (lexicalPutBtn) {
947
- lexicalPutBtn.addEventListener('click', async () => {
948
- const path = document.getElementById('lexical-path')?.value?.trim();
949
- const data = document.getElementById('lexical-data')?.value?.trim();
950
-
951
- if (!path || !data) {
952
- this.addLexicalLogEntry('❌ Error: Both path and data are required');
953
- return;
954
- }
955
-
956
- try {
957
- const parsedData = JSON.parse(data);
958
- const lex = this.mesh.distributedStorage.lexical();
959
- const pathParts = path.split('.');
960
-
961
- let current = lex;
962
- for (const part of pathParts) {
963
- current = current.get(part);
964
- }
965
-
966
- await current.put(parsedData);
967
- this.addLexicalLogEntry(`✅ Put data at path: ${path}`);
968
- } catch (error) {
969
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
970
- }
971
- });
972
- }
973
-
974
- if (lexicalGetBtn) {
975
- lexicalGetBtn.addEventListener('click', async () => {
976
- const path = document.getElementById('lexical-path')?.value?.trim();
977
- const property = document.getElementById('lexical-property')?.value?.trim();
978
-
979
- if (!path || !property) {
980
- this.addLexicalLogEntry('❌ Error: Both path and property are required');
981
- return;
982
- }
983
-
984
- try {
985
- const lex = this.mesh.distributedStorage.lexical();
986
- const pathParts = path.split('.');
987
-
988
- let current = lex;
989
- for (const part of pathParts) {
990
- current = current.get(part);
991
- }
992
-
993
- const value = await current.get(property).val();
994
- this.addLexicalLogEntry(`📄 ${path}.${property}: ${JSON.stringify(value)}`);
995
- } catch (error) {
996
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
997
- }
998
- });
999
- }
1000
-
1001
- if (lexicalValBtn) {
1002
- lexicalValBtn.addEventListener('click', async () => {
1003
- const path = document.getElementById('lexical-path')?.value?.trim();
1004
-
1005
- if (!path) {
1006
- this.addLexicalLogEntry('❌ Error: Path is required');
1007
- return;
1008
- }
1009
-
1010
- try {
1011
- const lex = this.mesh.distributedStorage.lexical();
1012
- const pathParts = path.split('.');
1013
-
1014
- let current = lex;
1015
- for (const part of pathParts) {
1016
- current = current.get(part);
1017
- }
1018
-
1019
- const value = await current.val();
1020
- this.addLexicalLogEntry(`📄 Full object at ${path}: ${JSON.stringify(value, null, 2)}`);
1021
- } catch (error) {
1022
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1023
- }
1024
- });
1025
- }
1026
-
1027
- if (lexicalUpdateBtn) {
1028
- lexicalUpdateBtn.addEventListener('click', async () => {
1029
- const path = document.getElementById('lexical-path')?.value?.trim();
1030
- const data = document.getElementById('lexical-data')?.value?.trim();
1031
-
1032
- if (!path || !data) {
1033
- this.addLexicalLogEntry('❌ Error: Both path and data are required');
1034
- return;
1035
- }
1036
-
1037
- try {
1038
- const parsedData = JSON.parse(data);
1039
- const lex = this.mesh.distributedStorage.lexical();
1040
- const pathParts = path.split('.');
1041
-
1042
- let current = lex;
1043
- for (const part of pathParts) {
1044
- current = current.get(part);
1045
- }
1046
-
1047
- await current.update(parsedData);
1048
- this.addLexicalLogEntry(`✅ Updated data at path: ${path}`);
1049
- } catch (error) {
1050
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1051
- }
1052
- });
1053
- }
1054
-
1055
- if (lexicalDeleteBtn) {
1056
- lexicalDeleteBtn.addEventListener('click', async () => {
1057
- const path = document.getElementById('lexical-path')?.value?.trim();
1058
-
1059
- if (!path) {
1060
- this.addLexicalLogEntry('❌ Error: Path is required');
1061
- return;
1062
- }
1063
-
1064
- try {
1065
- const lex = this.mesh.distributedStorage.lexical();
1066
- const pathParts = path.split('.');
1067
-
1068
- let current = lex;
1069
- for (const part of pathParts) {
1070
- current = current.get(part);
1071
- }
1072
-
1073
- await current.delete();
1074
- this.addLexicalLogEntry(`✅ Deleted data at path: ${path}`);
1075
- } catch (error) {
1076
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1077
- }
1078
- });
1079
- }
1080
-
1081
- // Set Operations Event Handlers
1082
- if (lexicalSetBtn) {
1083
- lexicalSetBtn.addEventListener('click', async () => {
1084
- const path = document.getElementById('lexical-set-path')?.value?.trim();
1085
- const data = document.getElementById('lexical-set-data')?.value?.trim();
1086
-
1087
- if (!path || !data) {
1088
- this.addLexicalLogEntry('❌ Error: Both path and data are required');
1089
- return;
1090
- }
1091
-
1092
- try {
1093
- const parsedData = JSON.parse(data);
1094
- const lex = this.mesh.distributedStorage.lexical();
1095
- const pathParts = path.split('.');
1096
-
1097
- let current = lex;
1098
- for (const part of pathParts) {
1099
- current = current.get(part);
1100
- }
1101
-
1102
- await current.set(parsedData);
1103
- this.addLexicalLogEntry(`✅ Set data at path: ${path}`);
1104
- } catch (error) {
1105
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1106
- }
1107
- });
1108
- }
1109
-
1110
- if (lexicalMapBtn) {
1111
- lexicalMapBtn.addEventListener('click', async () => {
1112
- const path = document.getElementById('lexical-set-path')?.value?.trim();
1113
-
1114
- if (!path) {
1115
- this.addLexicalLogEntry('❌ Error: Path is required');
1116
- return;
1117
- }
1118
-
1119
- try {
1120
- const lex = this.mesh.distributedStorage.lexical();
1121
- const pathParts = path.split('.');
1122
-
1123
- let current = lex;
1124
- for (const part of pathParts) {
1125
- current = current.get(part);
1126
- }
1127
-
1128
- const mapResults = [];
1129
- const unsubscribe = current.map().on((value, key) => {
1130
- mapResults.push({ key, value });
1131
- this.addLexicalLogEntry(`🗺️ Map result - ${key}: ${JSON.stringify(value)}`);
1132
- });
1133
-
1134
- // Stop mapping after a short delay
1135
- setTimeout(() => {
1136
- if (unsubscribe) unsubscribe();
1137
- this.addLexicalLogEntry(`✅ Map operation completed with ${mapResults.length} results`);
1138
- }, 1000);
1139
- } catch (error) {
1140
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1141
- }
1142
- });
1143
- }
1144
-
1145
- // Property Access Event Handlers
1146
- if (lexicalProxySetBtn) {
1147
- lexicalProxySetBtn.addEventListener('click', async () => {
1148
- const path = document.getElementById('lexical-proxy-path')?.value?.trim();
1149
- const value = document.getElementById('lexical-proxy-value')?.value?.trim();
1150
-
1151
- if (!path || !value) {
1152
- this.addLexicalLogEntry('❌ Error: Both path and value are required');
1153
- return;
1154
- }
1155
-
1156
- try {
1157
- const lex = this.mesh.distributedStorage.lexical();
1158
- const pathParts = path.split('.');
1159
-
1160
- // Use proxy property access
1161
- let current = lex;
1162
- for (const part of pathParts.slice(0, -1)) {
1163
- current = current[part];
1164
- }
1165
-
1166
- const lastPart = pathParts[pathParts.length - 1];
1167
- await current[lastPart].put(value);
1168
-
1169
- this.addLexicalLogEntry(`✅ Set via proxy: ${path} = ${value}`);
1170
- } catch (error) {
1171
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1172
- }
1173
- });
1174
- }
1175
-
1176
- if (lexicalProxyGetBtn) {
1177
- lexicalProxyGetBtn.addEventListener('click', async () => {
1178
- const path = document.getElementById('lexical-proxy-path')?.value?.trim();
1179
-
1180
- if (!path) {
1181
- this.addLexicalLogEntry('❌ Error: Path is required');
1182
- return;
1183
- }
1184
-
1185
- try {
1186
- const lex = this.mesh.distributedStorage.lexical();
1187
- const pathParts = path.split('.');
1188
-
1189
- // Use proxy property access
1190
- let current = lex;
1191
- for (const part of pathParts.slice(0, -1)) {
1192
- current = current[part];
1193
- }
1194
-
1195
- const lastPart = pathParts[pathParts.length - 1];
1196
- const value = await current[lastPart].val();
1197
-
1198
- this.addLexicalLogEntry(`📄 Proxy get ${path}: ${JSON.stringify(value)}`);
1199
- } catch (error) {
1200
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1201
- }
1202
- });
1203
- }
1204
-
1205
- // Utility Operations Event Handlers
1206
- if (lexicalExistsBtn) {
1207
- lexicalExistsBtn.addEventListener('click', async () => {
1208
- const path = document.getElementById('lexical-util-path')?.value?.trim();
1209
-
1210
- if (!path) {
1211
- this.addLexicalLogEntry('❌ Error: Path is required');
1212
- return;
1213
- }
1214
-
1215
- try {
1216
- const lex = this.mesh.distributedStorage.lexical();
1217
- const pathParts = path.split('.');
1218
-
1219
- let current = lex;
1220
- for (const part of pathParts) {
1221
- current = current.get(part);
1222
- }
1223
-
1224
- const exists = await current.exists();
1225
- this.addLexicalLogEntry(`🔍 ${path} exists: ${exists}`);
1226
- } catch (error) {
1227
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1228
- }
1229
- });
1230
- }
1231
-
1232
- if (lexicalKeysBtn) {
1233
- lexicalKeysBtn.addEventListener('click', async () => {
1234
- const path = document.getElementById('lexical-util-path')?.value?.trim();
1235
-
1236
- if (!path) {
1237
- this.addLexicalLogEntry('❌ Error: Path is required');
1238
- return;
1239
- }
1240
-
1241
- try {
1242
- const lex = this.mesh.distributedStorage.lexical();
1243
- const pathParts = path.split('.');
1244
-
1245
- let current = lex;
1246
- for (const part of pathParts) {
1247
- current = current.get(part);
1248
- }
1249
-
1250
- const keys = await current.keys();
1251
- this.addLexicalLogEntry(`🔑 Keys at ${path}: [${keys.join(', ')}]`);
1252
- } catch (error) {
1253
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1254
- }
1255
- });
1256
- }
1257
-
1258
- if (lexicalPathBtn) {
1259
- lexicalPathBtn.addEventListener('click', async () => {
1260
- const path = document.getElementById('lexical-util-path')?.value?.trim();
1261
-
1262
- if (!path) {
1263
- this.addLexicalLogEntry('❌ Error: Path is required');
1264
- return;
1265
- }
1266
-
1267
- try {
1268
- const lex = this.mesh.distributedStorage.lexical();
1269
- const pathParts = path.split('.');
1270
-
1271
- let current = lex;
1272
- for (const part of pathParts) {
1273
- current = current.get(part);
1274
- }
1275
-
1276
- const fullPath = current.getPath();
1277
- this.addLexicalLogEntry(`🛤️ Full storage path: ${fullPath}`);
1278
- } catch (error) {
1279
- this.addLexicalLogEntry(`❌ Error: ${error.message}`);
1280
- }
1281
- });
1282
- }
1283
- }
1284
-
1285
- async handleStorageStore(isUpdate = false) {
1286
- const key = document.getElementById('storage-key')?.value?.trim();
1287
- const value = document.getElementById('storage-value')?.value?.trim();
1288
- const encrypt = document.getElementById('storage-encrypt')?.checked ?? true;
1289
- const isPublic = document.getElementById('storage-public')?.checked ?? false;
1290
- const immutable = document.getElementById('storage-immutable')?.checked ?? false;
1291
- const enableCrdt = document.getElementById('storage-crdt')?.checked ?? false;
1292
- const ttl = parseInt(document.getElementById('storage-ttl')?.value) || 0;
1293
-
1294
- if (!key || !value) {
1295
- this.addStorageLogEntry('❌ Error: Both key and value are required');
1296
- return;
1297
- }
1298
-
1299
- try {
1300
- if (!this.mesh.distributedStorage) {
1301
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
1302
- return;
1303
- }
1304
-
1305
- let parsedValue;
1306
- try {
1307
- parsedValue = JSON.parse(value);
1308
- } catch {
1309
- parsedValue = value; // Use as string if not valid JSON
1310
- }
1311
-
1312
- const options = {
1313
- encrypt,
1314
- isPublic,
1315
- isImmutable: immutable,
1316
- enableCRDT: enableCrdt,
1317
- ttl: ttl > 0 ? ttl * 1000 : undefined // Convert to milliseconds
1318
- };
1319
-
1320
- let success;
1321
- if (isUpdate) {
1322
- success = await this.mesh.distributedStorage.update(key, parsedValue, options);
1323
- if (success) {
1324
- this.addStorageLogEntry(`🔄 Updated: ${key} = ${JSON.stringify(parsedValue)}`);
1325
- } else {
1326
- this.addStorageLogEntry(`❌ Failed to update: ${key}`);
1327
- }
1328
- } else {
1329
- success = await this.mesh.distributedStorage.store(key, parsedValue, options);
1330
- if (success) {
1331
- this.addStorageLogEntry(`💾 Stored: ${key} = ${JSON.stringify(parsedValue)}`);
1332
- } else {
1333
- this.addStorageLogEntry(`❌ Failed to store: ${key}`);
1334
- }
1335
- }
1336
-
1337
- if (success) {
1338
- const optionsStr = [];
1339
- if (encrypt) optionsStr.push('encrypted');
1340
- if (isPublic) optionsStr.push('public');
1341
- if (immutable) optionsStr.push('immutable');
1342
- if (enableCrdt) optionsStr.push('CRDT');
1343
- if (ttl > 0) optionsStr.push(`TTL: ${ttl}s`);
1344
-
1345
- if (optionsStr.length > 0) {
1346
- this.addStorageLogEntry(` Options: ${optionsStr.join(', ')}`);
1347
- }
1348
-
1349
- this.updateStorageStatus();
1350
- }
1351
- } catch (error) {
1352
- this.addStorageLogEntry(`❌ Error ${isUpdate ? 'updating' : 'storing'} ${key}: ${error.message}`);
1353
- }
1354
- }
1355
-
1356
- addStorageLogEntry(message) {
1357
- const logElement = document.getElementById('storage-log');
1358
- if (!logElement) return;
1359
-
1360
- const entry = document.createElement('div');
1361
- entry.className = 'log-entry';
1362
- entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
1363
-
1364
- logElement.appendChild(entry);
1365
- logElement.scrollTop = logElement.scrollHeight;
1366
-
1367
- // Keep only last 100 entries
1368
- while (logElement.children.length > 100) {
1369
- logElement.removeChild(logElement.firstChild);
1370
- }
1371
- }
1372
-
1373
- addLexicalLogEntry(message) {
1374
- const logElement = document.getElementById('lexical-log');
1375
- if (!logElement) return;
1376
-
1377
- const entry = document.createElement('div');
1378
- entry.className = 'log-entry';
1379
- entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
1380
-
1381
- logElement.appendChild(entry);
1382
- logElement.scrollTop = logElement.scrollHeight;
1383
-
1384
- // Keep only last 100 entries
1385
- while (logElement.children.length > 100) {
1386
- logElement.removeChild(logElement.firstChild);
1387
- }
1388
- }
1389
-
1390
- updateStorageStatus() {
1391
- if (!this.mesh.distributedStorage) {
1392
- document.getElementById('storage-status').textContent = 'Not Available';
1393
- document.getElementById('storage-item-count').textContent = '0';
1394
- document.getElementById('storage-total-size').textContent = '0 bytes';
1395
- return;
1396
- }
1397
-
1398
- const isEnabled = this.mesh.distributedStorage.isEnabled();
1399
- document.getElementById('storage-status').textContent = isEnabled ? 'Enabled' : 'Disabled';
1400
-
1401
- // Get storage stats if available
1402
- this.mesh.distributedStorage.getStats().then(stats => {
1403
- document.getElementById('storage-item-count').textContent = stats.itemCount.toString();
1404
- document.getElementById('storage-total-size').textContent = this.formatBytes(stats.totalSize);
1405
- }).catch(() => {
1406
- document.getElementById('storage-item-count').textContent = '0';
1407
- document.getElementById('storage-total-size').textContent = '0 bytes';
1408
- });
1409
- }
1410
-
1411
- formatBytes(bytes) {
1412
- if (bytes === 0) return '0 bytes';
1413
- const k = 1024;
1414
- const sizes = ['bytes', 'KB', 'MB', 'GB'];
1415
- const i = Math.floor(Math.log(bytes) / Math.log(k));
1416
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
1417
- }
1418
-
1419
- setupCryptoControls() {
1420
- // Key Management Controls
1421
- const generateBtn = document.getElementById('crypto-generate-btn');
1422
- const resetBtn = document.getElementById('crypto-reset-btn');
1423
- const selfTestBtn = document.getElementById('crypto-self-test-btn');
1424
-
1425
- // User Authentication Controls
1426
- const loginBtn = document.getElementById('crypto-login-btn');
1427
- const aliasInput = document.getElementById('crypto-alias');
1428
- const passwordInput = document.getElementById('crypto-password');
1429
-
1430
- // Messaging Controls
1431
- const testMessageInput = document.getElementById('crypto-test-message');
1432
- const testPeerInput = document.getElementById('crypto-test-peer');
1433
- const sendEncryptedBtn = document.getElementById('crypto-send-encrypted-btn');
1434
-
1435
- // Group Encryption Controls
1436
- const groupIdInput = document.getElementById('crypto-group-id');
1437
- const createGroupBtn = document.getElementById('crypto-create-group-btn');
1438
- const groupMessageInput = document.getElementById('crypto-group-message');
1439
- const groupSelect = document.getElementById('crypto-group-select');
1440
- const sendGroupBtn = document.getElementById('crypto-send-group-btn');
1441
-
1442
- // Advanced Controls
1443
- const exportKeyBtn = document.getElementById('crypto-export-key-btn');
1444
- const importPeerKeyBtn = document.getElementById('crypto-import-peer-key-btn');
1445
- const benchmarkBtn = document.getElementById('crypto-benchmark-btn');
1446
-
1447
- // Import Form Controls
1448
- const importForm = document.getElementById('crypto-import-form');
1449
- const importPeerIdInput = document.getElementById('crypto-import-peer-id');
1450
- const importPublicKeyInput = document.getElementById('crypto-import-public-key');
1451
- const importConfirmBtn = document.getElementById('crypto-import-confirm-btn');
1452
- const importCancelBtn = document.getElementById('crypto-import-cancel-btn');
1453
-
1454
- // Key Management Event Handlers
1455
- if (generateBtn) {
1456
- generateBtn.addEventListener('click', async () => {
1457
- try {
1458
- this.addCryptoTestResult('🔄 Generating new keypair...', 'info');
1459
- await this.mesh.initCrypto({ generateKeypair: true });
1460
- this.addCryptoTestResult('✅ New keypair generated successfully', 'success');
1461
- this.updateCryptoStatus();
1462
- } catch (error) {
1463
- this.addCryptoTestResult(`❌ Failed to generate keypair: ${error.message}`, 'error');
1464
- }
1465
- });
1466
- }
1467
-
1468
- if (resetBtn) {
1469
- resetBtn.addEventListener('click', () => {
1470
- if (confirm('This will clear all crypto keys and reset the crypto system. Continue?')) {
1471
- try {
1472
- this.mesh.resetCrypto();
1473
- this.addCryptoTestResult('✅ Crypto system reset', 'success');
1474
- this.updateCryptoStatus();
1475
- this.clearCryptoTestResults();
1476
- } catch (error) {
1477
- this.addCryptoTestResult(`❌ Failed to reset crypto: ${error.message}`, 'error');
1478
- }
1479
- }
1480
- });
1481
- }
1482
-
1483
- if (selfTestBtn) {
1484
- selfTestBtn.addEventListener('click', async () => {
1485
- try {
1486
- this.addCryptoTestResult('🔄 Running crypto self-tests...', 'info');
1487
- const results = await this.mesh.runCryptoTests();
1488
-
1489
- // Handle the actual format returned by CryptoManager
1490
- if (results.keypairGeneration !== undefined) {
1491
- const status = results.keypairGeneration ? '✅' : '❌';
1492
- const type = results.keypairGeneration ? 'success' : 'error';
1493
- this.addCryptoTestResult(`${status} keypairGeneration: ${results.keypairGeneration}`, type);
1494
- }
1495
-
1496
- if (results.encryption !== undefined) {
1497
- const status = results.encryption ? '✅' : '❌';
1498
- const type = results.encryption ? 'success' : 'error';
1499
- this.addCryptoTestResult(`${status} encryption: ${results.encryption}`, type);
1500
- }
1501
-
1502
- if (results.decryption !== undefined) {
1503
- const status = results.decryption ? '✅' : '❌';
1504
- const type = results.decryption ? 'success' : 'error';
1505
- this.addCryptoTestResult(`${status} decryption: ${results.decryption}`, type);
1506
- }
1507
-
1508
- if (results.signing !== undefined) {
1509
- const status = results.signing ? '✅' : '❌';
1510
- const type = results.signing ? 'success' : 'error';
1511
- this.addCryptoTestResult(`${status} signing: ${results.signing}`, type);
1512
- }
1513
-
1514
- if (results.verification !== undefined) {
1515
- const status = results.verification ? '✅' : '❌';
1516
- const type = results.verification ? 'success' : 'error';
1517
- this.addCryptoTestResult(`${status} verification: ${results.verification}`, type);
1518
- }
1519
-
1520
- if (results.groupEncryption !== undefined) {
1521
- const status = results.groupEncryption ? '✅' : '❌';
1522
- const type = results.groupEncryption ? 'success' : 'error';
1523
- this.addCryptoTestResult(`${status} groupEncryption: ${results.groupEncryption}`, type);
1524
- }
1525
-
1526
- if (results.errors && results.errors.length > 0) {
1527
- results.errors.forEach(error => {
1528
- this.addCryptoTestResult(`❌ errors: ${error}`, 'error');
1529
- });
1530
- }
1531
- } catch (error) {
1532
- this.addCryptoTestResult(`❌ Self-test failed: ${error.message}`, 'error');
1533
- }
1534
- });
1535
- }
1536
-
1537
- // User Authentication Event Handlers
1538
- if (loginBtn && aliasInput && passwordInput) {
1539
- loginBtn.addEventListener('click', async () => {
1540
- const alias = aliasInput.value.trim();
1541
- const password = passwordInput.value.trim();
1542
-
1543
- if (!alias || !password) {
1544
- this.addCryptoTestResult('❌ Both alias and password are required', 'error');
1545
- return;
1546
- }
1547
-
1548
- try {
1549
- this.addCryptoTestResult(`🔄 Authenticating as ${alias}...`, 'info');
1550
- await this.mesh.initCrypto({ alias, password });
1551
- this.addCryptoTestResult(`✅ Authenticated as ${alias}`, 'success');
1552
- this.updateCryptoStatus();
1553
-
1554
- // Clear password for security
1555
- passwordInput.value = '';
1556
- } catch (error) {
1557
- this.addCryptoTestResult(`❌ Authentication failed: ${error.message}`, 'error');
1558
- }
1559
- });
1560
- }
1561
-
1562
- // Messaging Event Handlers
1563
- if (sendEncryptedBtn && testMessageInput && testPeerInput) {
1564
- sendEncryptedBtn.addEventListener('click', async () => {
1565
- const message = testMessageInput.value.trim();
1566
- const peerId = testPeerInput.value.trim();
1567
-
1568
- if (!message) {
1569
- this.addCryptoTestResult('❌ Message is required', 'error');
1570
- return;
1571
- }
1572
-
1573
- if (!peerId) {
1574
- this.addCryptoTestResult('❌ Target peer ID is required', 'error');
1575
- return;
1576
- }
1577
-
1578
- try {
1579
- this.addCryptoTestResult(`🔄 Sending encrypted message to ${peerId.substring(0, 8)}...`, 'info');
1580
- await this.mesh.sendEncryptedMessage(peerId, message);
1581
- this.addCryptoTestResult('✅ Encrypted message sent', 'success');
1582
- testMessageInput.value = '';
1583
- } catch (error) {
1584
- this.addCryptoTestResult(`❌ Failed to send encrypted message: ${error.message}`, 'error');
1585
- }
1586
- });
1587
- }
1588
-
1589
- // Group Encryption Event Handlers
1590
- if (createGroupBtn && groupIdInput) {
1591
- createGroupBtn.addEventListener('click', async () => {
1592
- const groupId = groupIdInput.value.trim();
1593
-
1594
- if (!groupId) {
1595
- this.addCryptoTestResult('❌ Group ID is required', 'error');
1596
- return;
1597
- }
1598
-
1599
- try {
1600
- this.addCryptoTestResult(`🔄 Creating group key for ${groupId}...`, 'info');
1601
- await this.mesh.generateGroupKey(groupId);
1602
- this.addCryptoTestResult(`✅ Group key created for ${groupId}`, 'success');
1603
- this.updateGroupSelect();
1604
- groupIdInput.value = '';
1605
- } catch (error) {
1606
- this.addCryptoTestResult(`❌ Failed to create group key: ${error.message}`, 'error');
1607
- }
1608
- });
1609
- }
1610
-
1611
- if (sendGroupBtn && groupMessageInput && groupSelect) {
1612
- sendGroupBtn.addEventListener('click', async () => {
1613
- const message = groupMessageInput.value.trim();
1614
- const groupId = groupSelect.value;
1615
-
1616
- if (!message) {
1617
- this.addCryptoTestResult('❌ Group message is required', 'error');
1618
- return;
1619
- }
1620
-
1621
- if (!groupId) {
1622
- this.addCryptoTestResult('❌ Please select a group', 'error');
1623
- return;
1624
- }
1625
-
1626
- try {
1627
- this.addCryptoTestResult(`🔄 Sending encrypted group message to ${groupId}...`, 'info');
1628
- await this.mesh.sendEncryptedBroadcast(message, groupId);
1629
- this.addCryptoTestResult('✅ Encrypted group message sent', 'success');
1630
- groupMessageInput.value = '';
1631
- } catch (error) {
1632
- this.addCryptoTestResult(`❌ Failed to send group message: ${error.message}`, 'error');
1633
- }
1634
- });
1635
- }
1636
-
1637
- // Advanced Controls Event Handlers
1638
- if (exportKeyBtn) {
1639
- exportKeyBtn.addEventListener('click', () => {
1640
- try {
1641
- const keyData = this.mesh.exportPublicKey();
1642
- if (keyData) {
1643
- const exportText = JSON.stringify(keyData, null, 2);
1644
- navigator.clipboard.writeText(exportText).then(() => {
1645
- this.addCryptoTestResult('✅ Public key copied to clipboard', 'success');
1646
- }).catch(() => {
1647
- // Fallback - show in alert
1648
- alert('Public Key:\n\n' + exportText);
1649
- this.addCryptoTestResult('✅ Public key exported (check dialog)', 'success');
1650
- });
1651
- } else {
1652
- this.addCryptoTestResult('❌ No public key available to export', 'error');
1653
- }
1654
- } catch (error) {
1655
- this.addCryptoTestResult(`❌ Failed to export key: ${error.message}`, 'error');
1656
- }
1657
- });
1658
- }
1659
-
1660
- if (importPeerKeyBtn && importForm) {
1661
- importPeerKeyBtn.addEventListener('click', () => {
1662
- importForm.style.display = importForm.style.display === 'none' ? 'block' : 'none';
1663
- });
1664
- }
1665
-
1666
- if (importConfirmBtn && importPeerIdInput && importPublicKeyInput && importForm) {
1667
- importConfirmBtn.addEventListener('click', () => {
1668
- const peerId = importPeerIdInput.value.trim();
1669
- const publicKey = importPublicKeyInput.value.trim();
1670
-
1671
- if (!peerId || peerId.length !== 40) {
1672
- this.addCryptoTestResult('❌ Valid 40-character peer ID is required', 'error');
1673
- return;
1674
- }
1675
-
1676
- if (!publicKey) {
1677
- this.addCryptoTestResult('❌ Public key is required', 'error');
1678
- return;
1679
- }
1680
-
1681
- try {
1682
- // Try to parse as JSON first (for full keypair with pub/epub)
1683
- let keyData;
1684
- try {
1685
- keyData = JSON.parse(publicKey);
1686
- // Validate that it has the expected structure
1687
- if (!keyData.pub && !keyData.epub && !keyData.publicKey) {
1688
- throw new Error('Invalid key format');
1689
- }
1690
- } catch (jsonError) {
1691
- // If JSON parsing fails, treat as plain string (legacy format)
1692
- keyData = publicKey;
1693
- }
1694
-
1695
- const success = this.mesh.addPeerPublicKey(peerId, keyData);
1696
- if (success) {
1697
- const keyType = typeof keyData === 'object'
1698
- ? (keyData.pub && keyData.epub ? 'complete keypair' : 'partial key')
1699
- : 'legacy key';
1700
- this.addCryptoTestResult(`✅ Public key imported for ${peerId.substring(0, 8)}... (${keyType})`, 'success');
1701
- if (typeof keyData === 'string' || !keyData.epub) {
1702
- this.addCryptoTestResult('⚠️ Warning: Only signing key imported. Encryption may not work.', 'warning');
1703
- }
1704
- this.updateCryptoStatus();
1705
- importPeerIdInput.value = '';
1706
- importPublicKeyInput.value = '';
1707
- importForm.style.display = 'none';
1708
- } else {
1709
- this.addCryptoTestResult('❌ Failed to import public key', 'error');
1710
- }
1711
- } catch (error) {
1712
- this.addCryptoTestResult(`❌ Failed to import key: ${error.message}`, 'error');
1713
- }
1714
- });
1715
- }
1716
-
1717
- if (importCancelBtn && importForm) {
1718
- importCancelBtn.addEventListener('click', () => {
1719
- importForm.style.display = 'none';
1720
- if (importPeerIdInput) importPeerIdInput.value = '';
1721
- if (importPublicKeyInput) importPublicKeyInput.value = '';
1722
- });
1723
- }
1724
-
1725
- if (benchmarkBtn) {
1726
- benchmarkBtn.addEventListener('click', async () => {
1727
- try {
1728
- this.addCryptoTestResult('🔄 Running crypto benchmark...', 'info');
1729
-
1730
- const testData = 'This is a test message for benchmarking crypto performance.';
1731
- const iterations = 100;
1732
-
1733
- // Test encryption/decryption performance
1734
- const startTime = performance.now();
1735
- for (let i = 0; i < iterations; i++) {
1736
- const encrypted = await this.mesh.encryptMessage(testData);
1737
- await this.mesh.decryptMessage(encrypted);
1738
- }
1739
- const endTime = performance.now();
1740
-
1741
- const totalTime = endTime - startTime;
1742
- const avgTime = totalTime / iterations;
1743
-
1744
- this.addCryptoTestResult(`✅ Benchmark completed: ${iterations} iterations`, 'success');
1745
- this.addCryptoTestResult(` Total time: ${totalTime.toFixed(2)}ms`, 'info');
1746
- this.addCryptoTestResult(` Average time per cycle: ${avgTime.toFixed(2)}ms`, 'info');
1747
- } catch (error) {
1748
- this.addCryptoTestResult(`❌ Benchmark failed: ${error.message}`, 'error');
1749
- }
1750
- });
1751
- }
1752
- }
1753
-
1754
- setupMediaControls() {
1755
- // Start media button
1756
- document.getElementById('start-media-btn').addEventListener('click', async () => {
1757
- await this.startMedia();
1758
- });
1759
-
1760
- // Stop media button
1761
- document.getElementById('stop-media-btn').addEventListener('click', async () => {
1762
- await this.stopMedia();
1763
- });
1764
-
1765
- // Toggle video button
1766
- document.getElementById('toggle-video-btn').addEventListener('click', () => {
1767
- this.toggleVideo();
1768
- });
1769
-
1770
- // Toggle audio button
1771
- document.getElementById('toggle-audio-btn').addEventListener('click', () => {
1772
- this.toggleAudio();
1773
- });
1774
-
1775
- // Audio test button
1776
- document.getElementById('test-audio-btn').addEventListener('click', () => {
1777
- this.testAudio();
1778
- });
1779
-
1780
- // Media type checkboxes
1781
- document.getElementById('enable-video').addEventListener('change', () => {
1782
- this.updateMediaButtonStates();
1783
- });
1784
-
1785
- document.getElementById('enable-audio').addEventListener('change', () => {
1786
- this.updateMediaButtonStates();
1787
- });
1788
-
1789
- // Device selection dropdowns
1790
- document.getElementById('camera-select').addEventListener('change', () => {
1791
- // Auto-restart media if it's currently active
1792
- if (this.mesh.getMediaState().hasLocalStream) {
1793
- this.startMedia();
1794
- }
1795
- });
1796
-
1797
- document.getElementById('microphone-select').addEventListener('change', () => {
1798
- // Auto-restart media if it's currently active
1799
- if (this.mesh.getMediaState().hasLocalStream) {
1800
- this.startMedia();
1801
- }
1802
- });
1803
- }
1804
-
1805
- setupCollapsibleSections() {
1806
- const sections = [
1807
- 'discovered-peers',
1808
- 'connected-peers',
1809
- 'manual-connection',
1810
- 'settings',
1811
- 'dht',
1812
- 'storage',
1813
- 'crypto',
1814
- 'media'
1815
- ];
1816
-
1817
- sections.forEach(sectionId => {
1818
- const toggle = document.getElementById(`${sectionId}-toggle`);
1819
- const content = document.getElementById(`${sectionId}-content`);
1820
- const section = document.querySelector(`.${sectionId}`);
1821
-
1822
- if (toggle && content && section) {
1823
- // Force all sections to start collapsed with multiple approaches
1824
- section.setAttribute('aria-expanded', 'false');
1825
- toggle.setAttribute('aria-expanded', 'false');
1826
-
1827
- // Use multiple ways to hide the content
1828
- content.style.display = 'none';
1829
- content.style.visibility = 'hidden';
1830
- content.style.maxHeight = '0';
1831
- content.style.overflow = 'hidden';
1832
- content.classList.add('collapsed');
1833
-
1834
- // Ensure the toggle button shows collapsed state
1835
- if (toggle.textContent && !toggle.textContent.includes('▶')) {
1836
- toggle.textContent = toggle.textContent.replace('▼', '▶');
1837
- }
1838
-
1839
- toggle.addEventListener('click', () => {
1840
- this.toggleSection(sectionId);
1841
- });
1842
- }
1843
- });
1844
- }
1845
-
1846
- toggleSection(sectionId) {
1847
- const toggle = document.getElementById(`${sectionId}-toggle`);
1848
- const content = document.getElementById(`${sectionId}-content`);
1849
-
1850
- if (!toggle || !content) {
1851
- console.warn(`Could not find elements for section: ${sectionId}`);
1852
- return;
1853
- }
1854
-
1855
- const section = toggle.closest(`.${sectionId}`);
1856
-
1857
- if (!section) {
1858
- console.warn(`Could not find section container for: ${sectionId}`, {
1859
- toggle,
1860
- toggleParent: toggle.parentElement,
1861
- toggleParentParent: toggle.parentElement?.parentElement,
1862
- classList: toggle.parentElement?.parentElement?.classList
1863
- });
1864
- return;
1865
- }
1866
-
1867
- const isExpanded = toggle.getAttribute('aria-expanded') === 'true';
1868
-
1869
- toggle.setAttribute('aria-expanded', !isExpanded);
1870
-
1871
- // Add null check before calling setAttribute
1872
- if (section) {
1873
- section.setAttribute('aria-expanded', !isExpanded);
1874
- }
1875
-
1876
- if (isExpanded) {
1877
- // Collapse - hide with multiple approaches
1878
- content.style.display = 'none';
1879
- content.style.visibility = 'hidden';
1880
- content.style.maxHeight = '0';
1881
- content.style.overflow = 'hidden';
1882
- content.classList.add('collapsed');
1883
- toggle.textContent = toggle.textContent.replace('▼', '▶');
1884
- } else {
1885
- // Expand - show and reset styles
1886
- content.style.display = 'block';
1887
- content.style.visibility = 'visible';
1888
- content.style.maxHeight = 'none';
1889
- content.style.overflow = 'visible';
1890
- content.classList.remove('collapsed');
1891
- toggle.textContent = toggle.textContent.replace('▶', '▼');
1892
- }
1893
- }
1894
-
1895
- // Media-related methods
1896
- async initializeMedia() {
1897
- try {
1898
- // Initialize media manager
1899
- await this.mesh.initializeMedia();
1900
-
1901
- // Populate device lists
1902
- await this.updateDeviceLists();
1903
-
1904
- // Update button states
1905
- this.updateMediaButtonStates();
1906
-
1907
- console.log('Media initialized successfully');
1908
- } catch (error) {
1909
- console.error('Failed to initialize media:', error);
1910
- this.addMessage('System', `Failed to initialize media: ${error.message}`, 'error');
1911
- }
1912
- }
1913
-
1914
- async updateDeviceLists() {
1915
- try {
1916
- const devices = await this.mesh.enumerateMediaDevices();
1917
-
1918
- // Update camera list
1919
- const cameraSelect = document.getElementById('camera-select');
1920
- if (cameraSelect) {
1921
- cameraSelect.innerHTML = '<option value="">Select camera...</option>';
1922
- devices.cameras.forEach(device => {
1923
- const option = document.createElement('option');
1924
- option.value = device.deviceId;
1925
- option.textContent = device.label || `Camera ${device.deviceId.substring(0, 8)}...`;
1926
- cameraSelect.appendChild(option);
1927
- });
1928
- cameraSelect.disabled = devices.cameras.length === 0;
1929
- }
1930
-
1931
- // Update microphone list
1932
- const micSelect = document.getElementById('microphone-select');
1933
- if (micSelect) {
1934
- micSelect.innerHTML = '<option value="">Select microphone...</option>';
1935
- devices.microphones.forEach(device => {
1936
- const option = document.createElement('option');
1937
- option.value = device.deviceId;
1938
- option.textContent = device.label || `Microphone ${device.deviceId.substring(0, 8)}...`;
1939
- micSelect.appendChild(option);
1940
- });
1941
- micSelect.disabled = devices.microphones.length === 0;
1942
- }
1943
- } catch (error) {
1944
- console.error('Failed to update device lists:', error);
1945
- }
1946
- }
1947
-
1948
- updateMediaButtonStates() {
1949
- const videoEnabled = document.getElementById('enable-video')?.checked || false;
1950
- const audioEnabled = document.getElementById('enable-audio')?.checked || false;
1951
- const mediaState = this.mesh.getMediaState();
1952
-
1953
- // Enable start button if at least one media type is selected
1954
- const startBtn = document.getElementById('start-media-btn');
1955
- if (startBtn) {
1956
- startBtn.disabled = !(videoEnabled || audioEnabled) || mediaState.hasLocalStream;
1957
- }
1958
-
1959
- // Enable stop button if media is active
1960
- const stopBtn = document.getElementById('stop-media-btn');
1961
- if (stopBtn) {
1962
- stopBtn.disabled = !mediaState.hasLocalStream;
1963
- }
1964
-
1965
- // Enable toggle buttons if media is active
1966
- const toggleVideoBtn = document.getElementById('toggle-video-btn');
1967
- const toggleAudioBtn = document.getElementById('toggle-audio-btn');
1968
-
1969
- if (toggleVideoBtn) {
1970
- toggleVideoBtn.disabled = !mediaState.hasLocalStream;
1971
- toggleVideoBtn.textContent = mediaState.videoEnabled ? 'Turn Off Video' : 'Turn On Video';
1972
- }
1973
-
1974
- if (toggleAudioBtn) {
1975
- toggleAudioBtn.disabled = !mediaState.hasLocalStream;
1976
- toggleAudioBtn.textContent = mediaState.audioEnabled ? 'Turn Off Audio' : 'Turn On Audio';
1977
- }
1978
- }
1979
-
1980
- async startMedia() {
1981
- try {
1982
- const videoEnabled = document.getElementById('enable-video')?.checked || false;
1983
- const audioEnabled = document.getElementById('enable-audio')?.checked || false;
1984
-
1985
- // Initialize audio context for better audio support
1986
- if (audioEnabled && (window.AudioContext || window.webkitAudioContext)) {
1987
- const AudioContext = window.AudioContext || window.webkitAudioContext;
1988
- try {
1989
- const audioContext = new AudioContext();
1990
- if (audioContext.state === 'suspended') {
1991
- await audioContext.resume();
1992
- console.log('Audio context resumed for local media');
1993
- }
1994
- console.log('Audio context state:', audioContext.state);
1995
- } catch (e) {
1996
- console.log('Could not initialize audio context:', e);
1997
- }
1998
- }
1999
-
2000
- const deviceIds = {};
2001
- const cameraSelect = document.getElementById('camera-select');
2002
- const micSelect = document.getElementById('microphone-select');
2003
-
2004
- if (cameraSelect?.value) {
2005
- deviceIds.camera = cameraSelect.value;
2006
- }
2007
-
2008
- if (micSelect?.value) {
2009
- deviceIds.microphone = micSelect.value;
2010
- }
2011
-
2012
- await this.mesh.startMedia({
2013
- video: videoEnabled,
2014
- audio: audioEnabled,
2015
- deviceIds
2016
- });
2017
-
2018
- this.addMessage('System', 'Media started successfully');
2019
- this.updateMediaButtonStates();
2020
- } catch (error) {
2021
- console.error('Failed to start media:', error);
2022
- this.addMessage('System', `Failed to start media: ${error.message}`, 'error');
2023
- }
2024
- }
2025
-
2026
- async stopMedia() {
2027
- try {
2028
- await this.mesh.stopMedia();
2029
- this.addMessage('System', 'Media stopped');
2030
- this.updateMediaButtonStates();
2031
- this.clearLocalVideo();
2032
- } catch (error) {
2033
- console.error('Failed to stop media:', error);
2034
- this.addMessage('System', `Failed to stop media: ${error.message}`, 'error');
2035
- }
2036
- }
2037
-
2038
- toggleVideo() {
2039
- try {
2040
- const enabled = this.mesh.toggleVideo();
2041
- this.addMessage('System', `Video ${enabled ? 'enabled' : 'disabled'}`);
2042
- this.updateMediaButtonStates();
2043
- } catch (error) {
2044
- console.error('Failed to toggle video:', error);
2045
- this.addMessage('System', `Failed to toggle video: ${error.message}`, 'error');
2046
- }
2047
- }
2048
-
2049
- toggleAudio() {
2050
- try {
2051
- const enabled = this.mesh.toggleAudio();
2052
- this.addMessage('System', `Audio ${enabled ? 'enabled' : 'disabled'}`);
2053
- this.updateMediaButtonStates();
2054
- } catch (error) {
2055
- console.error('Failed to toggle audio:', error);
2056
- this.addMessage('System', `Failed to toggle audio: ${error.message}`, 'error');
2057
- }
2058
- }
2059
-
2060
- async testAudio() {
2061
- try {
2062
- console.log('🔊 Starting audio test...');
2063
- this.addMessage('System', '🔊 Testing audio system...', 'info');
2064
-
2065
- // First, run diagnostics to understand current state
2066
- this.logPeerDiagnostics();
2067
-
2068
- // Test 0: Verify we have actual peer connections (not just self)
2069
- const allPeers = this.mesh.getPeers();
2070
- const connectedPeers = allPeers.filter(peer => peer.status === 'connected');
2071
- const peersWithMedia = allPeers.filter(peer => {
2072
- const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
2073
- return peerConnection && (peerConnection.remoteStream || peerConnection.connection?.connectionState === 'connected');
2074
- });
2075
-
2076
- console.log('🔊 All peers:', allPeers.length);
2077
- console.log('🔊 Connected peers (data channel):', connectedPeers.length);
2078
- console.log('🔊 Peers with media/WebRTC:', peersWithMedia.length);
2079
-
2080
- // Log detailed peer status
2081
- allPeers.forEach(peer => {
2082
- const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
2083
- console.log(`🔊 Peer ${peer.peerId.substring(0, 8)}:`, {
2084
- status: peer.status,
2085
- webrtcState: peerConnection?.connection?.connectionState,
2086
- dataChannelState: peerConnection?.dataChannel?.readyState,
2087
- hasRemoteStream: !!peerConnection?.remoteStream,
2088
- hasLocalStream: !!peerConnection?.localStream
2089
- });
2090
- });
2091
-
2092
- this.addMessage('System', `🔊 Found ${allPeers.length} total peers (${connectedPeers.length} with data channel, ${peersWithMedia.length} with media)`, 'info');
2093
-
2094
- if (peersWithMedia.length === 0) {
2095
- this.addMessage('System', '❌ No peers with active media! You need to open this in TWO different browser tabs/windows and connect them.', 'error');
2096
- console.log('❌ NO PEERS WITH MEDIA: Open this URL in two different browser tabs and ensure they connect to each other');
2097
- return;
2098
- }
2099
-
2100
- // Test each peer connection individually
2101
- peersWithMedia.forEach((peer, index) => {
2102
- const connection = this.mesh.connectionManager.peers.get(peer.peerId);
2103
- if (connection) {
2104
- console.log(`🔊 Peer ${index + 1} (${peer.peerId.substring(0, 8)}...):`);
2105
-
2106
- const localStream = connection.getLocalStream();
2107
- const remoteStream = connection.getRemoteStream();
2108
-
2109
- // Check local stream
2110
- if (localStream) {
2111
- const localAudioTracks = localStream.getAudioTracks();
2112
- console.log(` - Local audio tracks: ${localAudioTracks.length}`);
2113
- this.addMessage('System', ` Peer ${index + 1} - Local audio: ${localAudioTracks.length} tracks`, 'info');
2114
- localAudioTracks.forEach((track, i) => {
2115
- console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}...`);
2116
- });
2117
- } else {
2118
- console.log(' - No local stream');
2119
- this.addMessage('System', ` Peer ${index + 1} - No local stream`, 'warning');
2120
- }
2121
-
2122
- // Check remote stream
2123
- if (remoteStream) {
2124
- const remoteAudioTracks = remoteStream.getAudioTracks();
2125
- console.log(` - Remote audio tracks: ${remoteAudioTracks.length}`);
2126
- this.addMessage('System', ` Peer ${index + 1} - Remote audio: ${remoteAudioTracks.length} tracks`, remoteAudioTracks.length > 0 ? 'success' : 'warning');
2127
-
2128
- remoteAudioTracks.forEach((track, i) => {
2129
- console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}..., readyState=${track.readyState}`);
2130
- });
2131
-
2132
- // CRITICAL: Check if remote stream ID matches local stream ID (loopback detection)
2133
- if (localStream && remoteStream.id === localStream.id) {
2134
- console.error('❌ LOOPBACK DETECTED: Remote stream ID matches local stream ID!');
2135
- this.addMessage('System', `❌ Peer ${index + 1} - LOOPBACK: Getting own audio back!`, 'error');
2136
- } else {
2137
- console.log(`✅ Stream IDs different: local=${localStream?.id.substring(0, 8) || 'none'}, remote=${remoteStream.id.substring(0, 8)}`);
2138
- this.addMessage('System', `✅ Peer ${index + 1} - Stream IDs are different (good!)`, 'success');
2139
- }
2140
-
2141
- // Check video elements playing this stream
2142
- const videoElements = document.querySelectorAll('video');
2143
- let foundVideoElement = false;
2144
- videoElements.forEach(video => {
2145
- if (video.srcObject === remoteStream) {
2146
- foundVideoElement = true;
2147
- console.log(` - Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}, readyState=${video.readyState}`);
2148
- this.addMessage('System', ` Peer ${index + 1} - Video element: volume=${video.volume}, muted=${video.muted}`, video.muted ? 'warning' : 'success');
2149
- }
2150
- });
2151
-
2152
- if (!foundVideoElement) {
2153
- console.log(' - ❌ No video element found for this remote stream');
2154
- this.addMessage('System', ` Peer ${index + 1} - ❌ No video element displaying this stream`, 'error');
2155
- }
2156
- } else {
2157
- console.log(' - ❌ No remote stream');
2158
- this.addMessage('System', ` Peer ${index + 1} - ❌ No remote stream received`, 'error');
2159
- }
2160
- } else {
2161
- console.log(`❌ No connection object found for peer ${peer.peerId}`);
2162
- this.addMessage('System', `❌ No connection for peer ${index + 1}`, 'error');
2163
- }
2164
- });
2165
-
2166
- // Test 1: Audio Context
2167
- if (window.AudioContext || window.webkitAudioContext) {
2168
- const AudioContext = window.AudioContext || window.webkitAudioContext;
2169
- const audioContext = new AudioContext();
2170
- console.log('Audio context state:', audioContext.state);
2171
-
2172
- if (audioContext.state === 'suspended') {
2173
- await audioContext.resume();
2174
- console.log('Audio context resumed');
2175
- }
2176
-
2177
- // Generate a test tone
2178
- const oscillator = audioContext.createOscillator();
2179
- const gainNode = audioContext.createGain();
2180
-
2181
- oscillator.connect(gainNode);
2182
- gainNode.connect(audioContext.destination);
2183
-
2184
- oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4 note
2185
- gainNode.gain.setValueAtTime(0.1, audioContext.currentTime); // Low volume
2186
-
2187
- oscillator.start();
2188
- oscillator.stop(audioContext.currentTime + 0.5); // Play for 0.5 seconds
2189
-
2190
- this.addMessage('System', '🔊 Audio test tone played (440Hz for 0.5s)', 'success');
2191
- } else {
2192
- this.addMessage('System', '❌ Audio context not supported', 'error');
2193
- }
2194
-
2195
- // Test 2: Check current media streams
2196
- const peers = this.mesh.getPeers();
2197
- console.log('Current peers:', peers.length);
2198
-
2199
- peers.forEach(peer => {
2200
- const connection = this.mesh.connectionManager.peers.get(peer.peerId);
2201
- if (connection) {
2202
- const localStream = connection.getLocalStream();
2203
- const remoteStream = connection.getRemoteStream();
2204
-
2205
- console.log(`Peer ${peer.peerId.substring(0, 8)}:`);
2206
- if (localStream) {
2207
- const audioTracks = localStream.getAudioTracks();
2208
- console.log(`- Local audio tracks: ${audioTracks.length}`);
2209
- audioTracks.forEach((track, i) => {
2210
- console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
2211
- });
2212
- }
2213
-
2214
- if (remoteStream) {
2215
- const audioTracks = remoteStream.getAudioTracks();
2216
- console.log(`- Remote audio tracks: ${audioTracks.length}`);
2217
- audioTracks.forEach((track, i) => {
2218
- console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
2219
- });
2220
-
2221
- // Check if there are video elements for this stream
2222
- const videoElements = document.querySelectorAll('video');
2223
- videoElements.forEach(video => {
2224
- if (video.srcObject === remoteStream) {
2225
- console.log(`- Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}`);
2226
- }
2227
- });
2228
- }
2229
- }
2230
- });
2231
-
2232
- // Test 3: Check microphone access
2233
- try {
2234
- const testStream = await navigator.mediaDevices.getUserMedia({ audio: true });
2235
- console.log('✅ Microphone access working');
2236
- this.addMessage('System', '✅ Microphone access: OK', 'success');
2237
- testStream.getTracks().forEach(track => track.stop());
2238
- } catch (error) {
2239
- console.log('❌ Microphone access failed:', error);
2240
- this.addMessage('System', `❌ Microphone access failed: ${error.message}`, 'error');
2241
- }
2242
- } catch (error) {
2243
- console.error('Audio test failed:', error);
2244
- this.addMessage('System', `❌ Audio test failed: ${error.message}`, 'error');
2245
- }
2246
- }
2247
-
2248
- handleLocalStreamStarted(data) {
2249
- this.updateMediaButtonStates();
2250
-
2251
- // Display local video if video is enabled
2252
- if (data.video) {
2253
- this.displayLocalVideo(data.stream);
2254
- }
2255
-
2256
- const mediaTypes = [];
2257
- if (data.video) mediaTypes.push('video');
2258
- if (data.audio) mediaTypes.push('audio');
2259
-
2260
- this.addMessage('System', `Local ${mediaTypes.join(' and ')} started`);
2261
- }
2262
-
2263
- handleLocalStreamStopped() {
2264
- this.updateMediaButtonStates();
2265
- this.clearLocalVideo();
2266
- this.addMessage('System', 'Local media stopped');
2267
- }
2268
-
2269
- displayLocalVideo(stream) {
2270
- const localVideoContainer = document.getElementById('local-video-container');
2271
- if (!localVideoContainer) return;
2272
-
2273
- let video = localVideoContainer.querySelector('video');
2274
- if (!video) {
2275
- video = document.createElement('video');
2276
- video.autoplay = true;
2277
- video.muted = true;
2278
- video.playsInline = true;
2279
- video.style.width = '100%';
2280
- video.style.borderRadius = '8px';
2281
- localVideoContainer.appendChild(video);
2282
- }
2283
-
2284
- video.srcObject = stream;
2285
- }
2286
-
2287
- clearLocalVideo() {
2288
- const localVideoContainer = document.getElementById('local-video-container');
2289
- if (localVideoContainer) {
2290
- const video = localVideoContainer.querySelector('video');
2291
- if (video) {
2292
- video.srcObject = null;
2293
- video.remove();
2294
- }
2295
- }
2296
- }
2297
-
2298
- handleRemoteStream(data) {
2299
- console.log('🎵 Handling remote stream:', data);
2300
- const { peerId, stream } = data;
2301
-
2302
- // CRITICAL: Prevent audio loopback - check if this is our own stream
2303
- if (peerId === this.mesh.peerId) {
2304
- console.warn('🚨 LOOPBACK DETECTED: Received our own stream as remote! This should not happen.');
2305
- console.warn('Stream ID:', stream.id);
2306
- // Still display it but it will be muted by displayRemoteVideo
2307
- }
2308
-
2309
- // Detailed audio analysis
2310
- const audioTracks = stream.getAudioTracks();
2311
- const videoTracks = stream.getVideoTracks();
2312
-
2313
- console.log(`Stream from ${peerId.substring(0, 8)}: ${audioTracks.length} audio, ${videoTracks.length} video tracks`);
2314
-
2315
- audioTracks.forEach((track, i) => {
2316
- console.log(`🎵 Audio track ${i}:`, {
2317
- id: track.id,
2318
- kind: track.kind,
2319
- enabled: track.enabled,
2320
- readyState: track.readyState,
2321
- muted: track.muted,
2322
- label: track.label
2323
- });
2324
-
2325
- // Add track event listeners for state monitoring
2326
- track.addEventListener('ended', () => {
2327
- console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} ENDED`);
2328
- });
2329
-
2330
- track.addEventListener('mute', () => {
2331
- console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} MUTED`);
2332
- });
2333
-
2334
- track.addEventListener('unmute', () => {
2335
- console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} UNMUTED`);
2336
- });
2337
- });
2338
-
2339
- this.displayRemoteVideo(peerId, stream);
2340
-
2341
- // Audio data summary
2342
- const audioSummary = {
2343
- peerIdShort: peerId.substring(0, 8),
2344
- audioTrackCount: audioTracks.length,
2345
- videoTrackCount: videoTracks.length,
2346
- audioTracksEnabled: audioTracks.filter(t => t.enabled).length,
2347
- streamActive: stream.active,
2348
- streamId: stream.id
2349
- };
2350
-
2351
- console.log(`🎵 AUDIO DATA EXPECTATION for peer ${audioSummary.peerIdShort}:`, audioSummary);
2352
-
2353
- if (audioTracks.length > 0) {
2354
- console.log(`✅ EXPECTING AUDIO DATA from peer ${audioSummary.peerIdShort} - ${audioSummary.audioTracksEnabled}/${audioSummary.audioTrackCount} tracks enabled`);
2355
- } else {
2356
- console.log(`❌ NO AUDIO TRACKS from peer ${audioSummary.peerIdShort} - video only`);
2357
- }
2358
-
2359
- this.addMessage('System', `🎵 Remote stream received from ${peerId.substring(0, 8)}... (${audioTracks.length} audio, ${videoTracks.length} video)`);
2360
- }
2361
-
2362
- displayRemoteVideo(peerId, stream) {
2363
- console.log(`Displaying remote video for ${peerId}:`, stream);
2364
- console.log('Stream tracks:', stream.getTracks().map(t => ({ kind: t.kind, enabled: t.enabled })));
2365
-
2366
- // CRITICAL: Prevent audio loopback - check if this is our own stream
2367
- const isOwnStream = peerId === this.mesh.peerId;
2368
- if (isOwnStream) {
2369
- console.warn('🚨 LOOPBACK DETECTED: Received our own stream! Muting audio to prevent feedback.');
2370
- }
2371
-
2372
- const remoteVideosContainer = document.getElementById('remote-videos-container');
2373
- if (!remoteVideosContainer) return;
2374
-
2375
- let remoteVideoItem = remoteVideosContainer.querySelector(`[data-peer-id="${peerId}"]`);
2376
-
2377
- if (!remoteVideoItem) {
2378
- remoteVideoItem = document.createElement('div');
2379
- remoteVideoItem.className = 'remote-video-item';
2380
- remoteVideoItem.setAttribute('data-peer-id', peerId);
2381
-
2382
- const title = document.createElement('div');
2383
- title.className = 'video-title';
2384
- title.textContent = `Peer ${peerId.substring(0, 8)}...`;
2385
-
2386
- const video = document.createElement('video');
2387
- video.autoplay = true;
2388
- video.playsInline = true;
2389
- video.controls = true;
2390
- // CRITICAL: Mute if this is our own stream to prevent audio feedback
2391
- video.muted = isOwnStream; // Mute our own audio, unmute others
2392
- video.style.width = '100%';
2393
- video.style.borderRadius = '8px';
2394
-
2395
- // Enhanced audio debugging
2396
- video.addEventListener('loadedmetadata', () => {
2397
- console.log('Video element loaded metadata:', {
2398
- duration: video.duration,
2399
- audioTracks: video.audioTracks?.length || 'N/A',
2400
- volume: video.volume,
2401
- muted: video.muted
2402
- });
2403
-
2404
- video.play().then(() => {
2405
- console.log('Video/audio playback started successfully');
2406
- // Check audio context state
2407
- if (window.AudioContext || window.webkitAudioContext) {
2408
- const AudioContext = window.AudioContext || window.webkitAudioContext;
2409
- const audioContext = new AudioContext();
2410
- console.log('Audio context state:', audioContext.state);
2411
- if (audioContext.state === 'suspended') {
2412
- console.log('Audio context is suspended - may need user interaction');
2413
- }
2414
- }
2415
- // Hide any play button if playback started
2416
- const playButton = remoteVideoItem.querySelector('.manual-play-button');
2417
- if (playButton) {
2418
- playButton.style.display = 'none';
2419
- }
2420
- }).catch(error => {
2421
- console.log('Autoplay failed, user interaction required:', error);
2422
- // Show a manual play button
2423
- const playButton = document.createElement('button');
2424
- playButton.className = 'manual-play-button';
2425
- playButton.textContent = '▶ Click to Play Audio';
2426
- 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;';
2427
-
2428
- playButton.addEventListener('click', async () => {
2429
- try {
2430
- await video.play();
2431
- playButton.style.display = 'none';
2432
- console.log('Manual play successful');
2433
- } catch (e) {
2434
- console.error('Manual play failed:', e);
2435
- }
2436
- });
2437
-
2438
- remoteVideoItem.style.position = 'relative';
2439
- remoteVideoItem.appendChild(playButton);
2440
- });
2441
- });
2442
-
2443
- // Add event listeners for audio debugging
2444
- video.addEventListener('play', () => {
2445
- console.log('Video element started playing');
2446
- });
2447
-
2448
- video.addEventListener('pause', () => {
2449
- console.log('Video element paused');
2450
- });
2451
-
2452
- video.addEventListener('volumechange', () => {
2453
- console.log('Volume changed:', video.volume, 'Muted:', video.muted);
2454
- });
2455
-
2456
- const status = document.createElement('div');
2457
- status.className = 'video-status';
2458
-
2459
- remoteVideoItem.appendChild(title);
2460
- remoteVideoItem.appendChild(video);
2461
- remoteVideoItem.appendChild(status);
2462
-
2463
- remoteVideosContainer.appendChild(remoteVideoItem);
2464
- }
2465
-
2466
- const video = remoteVideoItem.querySelector('video');
2467
- const status = remoteVideoItem.querySelector('.video-status');
2468
-
2469
- video.srcObject = stream;
2470
-
2471
- // EXPLICIT AUDIO DEBUGGING
2472
- console.log('🎵 Setting srcObject for video element:', {
2473
- stream,
2474
- streamId: stream.id,
2475
- streamActive: stream.active,
2476
- videoElement: video,
2477
- videoMuted: video.muted,
2478
- videoVolume: video.volume,
2479
- isOwnStream
2480
- });
2481
-
2482
- const audioTracks = stream.getAudioTracks();
2483
- const videoTracks = stream.getVideoTracks();
2484
-
2485
- console.log('🎵 Stream tracks assigned:', {
2486
- audioTracks: audioTracks.map(t => ({
2487
- id: t.id,
2488
- enabled: t.enabled,
2489
- readyState: t.readyState,
2490
- muted: t.muted
2491
- })),
2492
- videoTracks: videoTracks.map(t => ({
2493
- id: t.id,
2494
- enabled: t.enabled,
2495
- readyState: t.readyState,
2496
- muted: t.muted
2497
- }))
2498
- });
2499
-
2500
- // CRITICAL: Set audio state based on whether this is our own stream
2501
- if (isOwnStream) {
2502
- console.warn('🚨 Muting our own stream to prevent audio feedback');
2503
- video.muted = true;
2504
- video.volume = 0;
2505
- } else {
2506
- // Only unmute if this is NOT our own stream
2507
- video.muted = false;
2508
- video.volume = 1.0;
2509
-
2510
- // Setup audio playback monitoring for remote streams
2511
- this.setupAudioPlaybackMonitoring(video, peerId, audioTracks);
2512
- }
2513
-
2514
- // Update status based on stream tracks
2515
- console.log(`Video tracks: ${videoTracks.length}, Audio tracks: ${audioTracks.length}`);
2516
- audioTracks.forEach((track, i) => {
2517
- console.log(`Audio track ${i}:`, { enabled: track.enabled, muted: track.muted, label: track.label });
2518
- });
2519
-
2520
- // For audio-only streams, ensure the video element is properly configured
2521
- if (audioTracks.length > 0 && videoTracks.length === 0) {
2522
- console.log('Audio-only stream detected - configuring for audio playback');
2523
- video.style.height = '60px'; // Smaller height for audio-only
2524
- video.style.backgroundColor = '#f0f0f0';
2525
-
2526
- // Force audio to play by trying to resume audio context
2527
- if (window.AudioContext || window.webkitAudioContext) {
2528
- const AudioContext = window.AudioContext || window.webkitAudioContext;
2529
- try {
2530
- const audioContext = new AudioContext();
2531
- if (audioContext.state === 'suspended') {
2532
- audioContext.resume().then(() => {
2533
- console.log('Audio context resumed for remote stream');
2534
- });
2535
- }
2536
-
2537
- // Test audio by creating a brief analysis
2538
- try {
2539
- const source = audioContext.createMediaStreamSource(stream);
2540
- const analyser = audioContext.createAnalyser();
2541
- source.connect(analyser);
2542
-
2543
- const dataArray = new Uint8Array(analyser.frequencyBinCount);
2544
- const checkAudio = () => {
2545
- analyser.getByteFrequencyData(dataArray);
2546
- const sum = dataArray.reduce((a, b) => a + b, 0);
2547
- if (sum > 0) {
2548
- console.log('Remote audio data detected! Sum:', sum);
2549
- }
2550
- };
2551
-
2552
- // Check audio data periodically
2553
- const audioChecker = setInterval(checkAudio, 1000);
2554
- setTimeout(() => clearInterval(audioChecker), 10000); // Stop after 10 seconds
2555
- } catch (audioAnalysisError) {
2556
- console.log('Could not analyze remote audio:', audioAnalysisError);
2557
- }
2558
- } catch (e) {
2559
- console.log('Could not create/resume audio context:', e);
2560
- }
2561
- }
2562
- }
2563
-
2564
- const statusText = [];
2565
- if (videoTracks.length > 0) statusText.push('Video');
2566
- if (audioTracks.length > 0) statusText.push('Audio');
2567
-
2568
- status.textContent = statusText.length > 0 ? statusText.join(' + ') : 'Audio only';
2569
- status.style.color = '#28a745';
2570
-
2571
- this.addMessage('System', `Receiving ${statusText.join(' + ')} from ${peerId.substring(0, 8)}...`);
2572
- }
2573
-
2574
- /**
2575
- * Setup audio playback monitoring for video elements playing remote streams
2576
- */
2577
- setupAudioPlaybackMonitoring(videoElement, peerId, audioTracks) {
2578
- const peerIdShort = peerId.substring(0, 8);
2579
- console.log(`🎵 Setting up audio playback monitoring for peer ${peerIdShort}`);
2580
-
2581
- if (audioTracks.length === 0) {
2582
- console.log(`🎵 No audio tracks to monitor for peer ${peerIdShort}`);
2583
- return;
2584
- }
2585
-
2586
- try {
2587
- // Monitor video element audio events
2588
- videoElement.addEventListener('play', () => {
2589
- console.log(`🎵 Video element started playing for peer ${peerIdShort}`, {
2590
- muted: videoElement.muted,
2591
- volume: videoElement.volume,
2592
- audioTracks: audioTracks.length
2593
- });
2594
- });
2595
-
2596
- videoElement.addEventListener('pause', () => {
2597
- console.log(`🎵 Video element paused for peer ${peerIdShort}`);
2598
- });
2599
-
2600
- videoElement.addEventListener('volumechange', () => {
2601
- console.log(`🎵 Volume changed for peer ${peerIdShort}:`, {
2602
- volume: videoElement.volume,
2603
- muted: videoElement.muted
2604
- });
2605
- });
2606
-
2607
- // Create audio context for monitoring actual audio data playback
2608
- const AudioContext = window.AudioContext || window.webkitAudioContext;
2609
- if (!AudioContext) {
2610
- console.warn('🎵 AudioContext not available - basic monitoring only');
2611
- return;
2612
- }
2613
-
2614
- // Wait for video to load before setting up audio analysis
2615
- const setupAudioAnalysis = () => {
2616
- try {
2617
- const audioContext = new AudioContext();
2618
- const source = audioContext.createMediaElementSource(videoElement);
2619
- const analyser = audioContext.createAnalyser();
2620
- const gainNode = audioContext.createGain();
2621
-
2622
- analyser.fftSize = 256;
2623
- const bufferLength = analyser.frequencyBinCount;
2624
- const dataArray = new Uint8Array(bufferLength);
2625
-
2626
- // Connect: source -> analyser -> gain -> destination
2627
- source.connect(analyser);
2628
- analyser.connect(gainNode);
2629
- gainNode.connect(audioContext.destination);
2630
-
2631
- let lastLogTime = 0;
2632
- let totalSamples = 0;
2633
- let playbackSamples = 0;
2634
- let maxPlaybackLevel = 0;
2635
-
2636
- const monitorPlayback = () => {
2637
- if (videoElement.paused || videoElement.ended) {
2638
- return; // Stop monitoring if playback stopped
2639
- }
2640
-
2641
- analyser.getByteFrequencyData(dataArray);
2642
-
2643
- // Calculate playback audio level
2644
- const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
2645
- const currentTime = Date.now();
2646
-
2647
- totalSamples++;
2648
- if (average > 3) { // Lower threshold for playback detection
2649
- playbackSamples++;
2650
- maxPlaybackLevel = Math.max(maxPlaybackLevel, average);
2651
- }
2652
-
2653
- // Log every 3 seconds
2654
- if (currentTime - lastLogTime > 3000) {
2655
- const playbackActivity = totalSamples > 0 ? (playbackSamples / totalSamples * 100) : 0;
2656
- console.log(`🔊 Audio PLAYBACK from peer ${peerIdShort}:`, {
2657
- videoElementMuted: videoElement.muted,
2658
- videoElementVolume: videoElement.volume,
2659
- currentPlaybackLevel: Math.round(average),
2660
- maxPlaybackLevel: Math.round(maxPlaybackLevel),
2661
- playbackActivityPercent: Math.round(playbackActivity),
2662
- samplesAnalyzed: totalSamples,
2663
- audioBeingPlayed: playbackSamples > 0,
2664
- audioContextState: audioContext.state
2665
- });
2666
-
2667
- lastLogTime = currentTime;
2668
- totalSamples = 0;
2669
- playbackSamples = 0;
2670
- maxPlaybackLevel = 0;
2671
- }
2672
-
2673
- // Continue monitoring
2674
- if (!videoElement.paused && !videoElement.ended) {
2675
- requestAnimationFrame(monitorPlayback);
2676
- }
2677
- };
2678
-
2679
- // Start monitoring when video plays
2680
- videoElement.addEventListener('play', () => {
2681
- console.log(`🔊 Starting audio playback monitoring for peer ${peerIdShort}`);
2682
- if (audioContext.state === 'suspended') {
2683
- audioContext.resume().then(() => {
2684
- requestAnimationFrame(monitorPlayback);
2685
- });
2686
- } else {
2687
- requestAnimationFrame(monitorPlayback);
2688
- }
2689
- });
2690
-
2691
- console.log(`🔊 Audio playback analysis setup complete for peer ${peerIdShort}`);
2692
- } catch (error) {
2693
- console.error(`🔊 Failed to setup audio playback analysis for peer ${peerIdShort}:`, error);
2694
- }
2695
- };
2696
-
2697
- if (videoElement.readyState >= 1) {
2698
- // Video metadata already loaded
2699
- setupAudioAnalysis();
2700
- } else {
2701
- // Wait for metadata to load
2702
- videoElement.addEventListener('loadedmetadata', setupAudioAnalysis, { once: true });
2703
- }
2704
- } catch (error) {
2705
- console.error(`🎵 Failed to setup audio playback monitoring for peer ${peerIdShort}:`, error);
2706
- }
2707
- }
2708
-
2709
- /**
2710
- * Diagnostic method to log complete peer connection state
2711
- */
2712
- logPeerDiagnostics() {
2713
- console.log('🔍 PEER DIAGNOSTICS:');
2714
- const allPeers = this.mesh.getPeers();
2715
-
2716
- console.log(`📊 Total peers in mesh: ${allPeers.length}`);
2717
-
2718
- allPeers.forEach((peer, index) => {
2719
- const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
2720
-
2721
- console.log(`\n🔍 Peer ${index + 1}: ${peer.peerId.substring(0, 8)}...`);
2722
- console.log(` Status: ${peer.status}`);
2723
-
2724
- if (peerConnection) {
2725
- console.log(` WebRTC Connection State: ${peerConnection.connection?.connectionState || 'none'}`);
2726
- console.log(` ICE Connection State: ${peerConnection.connection?.iceConnectionState || 'none'}`);
2727
- console.log(` Data Channel State: ${peerConnection.dataChannel?.readyState || 'none'}`);
2728
- console.log(` Data Channel Ready: ${peerConnection.dataChannelReady}`);
2729
- console.log(` Has Local Stream: ${!!peerConnection.localStream}`);
2730
- console.log(` Has Remote Stream: ${!!peerConnection.remoteStream}`);
2731
-
2732
- if (peerConnection.localStream) {
2733
- const audioTracks = peerConnection.localStream.getAudioTracks();
2734
- const videoTracks = peerConnection.localStream.getVideoTracks();
2735
- console.log(` Local Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
2736
- }
2737
-
2738
- if (peerConnection.remoteStream) {
2739
- const audioTracks = peerConnection.remoteStream.getAudioTracks();
2740
- const videoTracks = peerConnection.remoteStream.getVideoTracks();
2741
- console.log(` Remote Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
2742
- }
2743
- } else {
2744
- console.log(' ❌ No PeerConnection object found');
2745
- }
2746
- });
2747
-
2748
- console.log('\n🔍 END PEER DIAGNOSTICS\n');
2749
- }
2750
-
2751
- // Existing UI methods (keeping the rest of the original functionality)
2752
- async handleConnect() {
2753
- const url = document.getElementById('signaling-url').value.trim();
2754
- if (!url) {
2755
- this.addMessage('System', 'Please enter a signaling server URL', 'error');
2756
- return;
2757
- }
2758
-
2759
- try {
2760
- this.updateButtonStates({ connecting: true });
2761
- await this.mesh.connect(url);
2762
- } catch (error) {
2763
- console.error('Connection failed:', error);
2764
- this.addMessage('System', `Connection failed: ${error.message}`, 'error');
2765
- this.updateButtonStates({ connecting: false });
2766
- }
2767
- }
2768
-
2769
- async handleDisconnect() {
2770
- try {
2771
- this.updateButtonStates({ disconnecting: true });
2772
- await this.mesh.disconnect();
2773
- } catch (error) {
2774
- console.error('Disconnection failed:', error);
2775
- this.addMessage('System', `Disconnection failed: ${error.message}`, 'error');
2776
- } finally {
2777
- this.updateButtonStates({ disconnecting: false });
2778
- }
2779
- }
2780
-
2781
- async handleCleanup() {
2782
- const now = Date.now();
2783
- const timeSinceLastCleanup = now - this.lastCleanupTime;
2784
-
2785
- if (timeSinceLastCleanup < 5000) {
2786
- const remaining = Math.ceil((5000 - timeSinceLastCleanup) / 1000);
2787
- this.addMessage('System', `Cleanup on cooldown (${remaining}s remaining)`, 'warning');
2788
- return;
2789
- }
2790
-
2791
- try {
2792
- this.lastCleanupTime = now;
2793
- await this.mesh.cleanupSignalingData();
2794
- this.addMessage('System', 'Signaling data cleanup initiated');
2795
- } catch (error) {
2796
- console.error('Cleanup failed:', error);
2797
- this.addMessage('System', `Cleanup failed: ${error.message}`, 'error');
2798
- }
2799
- }
2800
-
2801
- async handleHealthCheck() {
2802
- try {
2803
- const result = await this.mesh.performHealthCheck();
2804
- if (result.healthy) {
2805
- this.addMessage('System', 'Health check passed - all systems nominal', 'info');
2806
- } else {
2807
- this.addMessage('System', `Health check failed: ${result.issues.join(', ')}`, 'warning');
2808
- }
2809
- } catch (error) {
2810
- console.error('Health check failed:', error);
2811
- this.addMessage('System', `Health check error: ${error.message}`, 'error');
2812
- }
2813
- }
2814
-
2815
- async sendMessage() {
2816
- const messageInput = document.getElementById('message-input');
2817
- const dmTargetInput = document.getElementById('dm-target-input');
2818
- const autoEncryptToggle = document.getElementById('crypto-auto-encrypt');
2819
-
2820
- if (!messageInput) return;
2821
-
2822
- const message = messageInput.value.trim();
2823
- const dmTarget = dmTargetInput ? dmTargetInput.value.trim() : '';
2824
-
2825
- if (!message) return;
2826
-
2827
- try {
2828
- // Check if auto-encrypt is enabled and crypto is available
2829
- const shouldEncrypt = autoEncryptToggle && autoEncryptToggle.checked && this.mesh.getCryptoStatus().enabled;
2830
-
2831
- if (dmTarget) {
2832
- // Validate peer ID format for direct messages
2833
- if (!window.PeerPigeonMesh.validatePeerId(dmTarget)) {
2834
- this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
2835
- return;
2836
- }
2837
-
2838
- // Send direct message (encrypted or not)
2839
- if (shouldEncrypt) {
2840
- await this.mesh.sendEncryptedMessage(dmTarget, message);
2841
- this.addMessage('You', `🔐 (DM to ${dmTarget.substring(0, 8)}...) ${message}`, 'encrypted');
2842
- } else {
2843
- const success = this.mesh.sendDirectMessage(dmTarget, message);
2844
- if (success) {
2845
- this.addMessage('You', `(DM to ${dmTarget.substring(0, 8)}...) ${message}`, 'own');
2846
- } else {
2847
- this.addMessage('System', `Failed to send direct message to ${dmTarget.substring(0, 8)}...`, 'error');
2848
- }
2849
- }
2850
- } else {
2851
- // Send broadcast message (encrypted or not)
2852
- if (shouldEncrypt) {
2853
- // Get all connected peers for encryption
2854
- const connectedPeers = this.mesh.getPeers();
2855
- if (connectedPeers.length > 0) {
2856
- // Send encrypted message to all connected peers
2857
- for (const peer of connectedPeers) {
2858
- try {
2859
- await this.mesh.sendEncryptedMessage(peer.peerId, message);
2860
- } catch (error) {
2861
- console.warn(`Failed to send encrypted message to ${peer.peerId}:`, error);
2862
- }
2863
- }
2864
- this.addMessage('You', `🔐 ${message}`, 'encrypted');
2865
- } else {
2866
- this.addMessage('System', 'No connected peers to send encrypted message to', 'error');
2867
- }
2868
- } else {
2869
- // Send regular unencrypted message
2870
- this.mesh.sendMessage(message);
2871
- this.addMessage('You', message, 'own');
2872
- }
2873
- }
2874
-
2875
- messageInput.value = '';
2876
- } catch (error) {
2877
- console.error('Failed to send message:', error);
2878
- this.addMessage('System', `Failed to send message: ${error.message}`, 'error');
2879
- }
2880
- }
2881
-
2882
- connectToPeer() {
2883
- const targetPeerInput = document.getElementById('target-peer');
2884
- const targetPeerId = targetPeerInput.value.trim();
2885
-
2886
- if (!targetPeerId) {
2887
- this.addMessage('System', 'Please enter a peer ID', 'error');
2888
- return;
2889
- }
2890
-
2891
- if (!window.PeerPigeonMesh.validatePeerId(targetPeerId)) {
2892
- this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
2893
- return;
2894
- }
2895
-
2896
- if (targetPeerId === this.mesh.peerId) {
2897
- this.addMessage('System', 'Cannot connect to yourself', 'error');
2898
- return;
2899
- }
2900
-
2901
- try {
2902
- this.mesh.connectToPeer(targetPeerId);
2903
- this.addMessage('System', `Attempting to connect to ${targetPeerId.substring(0, 8)}...`);
2904
- targetPeerInput.value = '';
2905
- } catch (error) {
2906
- console.error('Failed to initiate connection:', error);
2907
- this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
2908
- }
2909
- }
2910
-
2911
- /**
2912
- * Connect to peer from button click (for onclick handlers)
2913
- */
2914
- connectToPeerFromButton(button) {
2915
- const peerId = button.getAttribute('data-peer-id');
2916
- if (!peerId) {
2917
- this.addMessage('System', 'Invalid peer ID in button', 'error');
2918
- return;
2919
- }
2920
-
2921
- // Disable button to prevent double-clicks
2922
- button.disabled = true;
2923
- button.textContent = 'Connecting...';
2924
-
2925
- try {
2926
- this.mesh.connectToPeer(peerId);
2927
- this.addMessage('System', `Attempting to connect to ${peerId.substring(0, 8)}...`);
2928
-
2929
- // Re-enable button after a delay
2930
- setTimeout(() => {
2931
- button.disabled = false;
2932
- button.textContent = 'Connect';
2933
- }, 3000);
2934
- } catch (error) {
2935
- console.error('Failed to initiate connection:', error);
2936
- this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
2937
-
2938
- // Re-enable button immediately on error
2939
- button.disabled = false;
2940
- button.textContent = 'Connect';
2941
- }
2942
- }
2943
-
2944
- updateUI() {
2945
- // Update peer ID display
2946
- const peerIdElement = document.getElementById('peer-id');
2947
- if (peerIdElement && this.mesh.peerId) {
2948
- peerIdElement.textContent = this.mesh.peerId;
2949
- }
2950
-
2951
- // Update status
2952
- this.updateStatus();
2953
-
2954
- // Update button states
2955
- this.updateButtonStates();
2956
-
2957
- // Update peer lists
2958
- this.updateConnectedPeers();
2959
- this.updateDiscoveredPeers();
2960
-
2961
- // Update settings from mesh state
2962
- this.updateSettings();
2963
-
2964
- // Update DHT status
2965
- this.updateDHTStatus();
2966
-
2967
- // Update storage status
2968
- this.updateStorageStatus();
2969
- }
2970
-
2971
- updateStatus() {
2972
- const statusElement = document.getElementById('status');
2973
- if (!statusElement) return;
2974
-
2975
- const status = this.mesh.getStatus();
2976
- const connectionStatus = status.connected ? 'connected' : 'disconnected';
2977
- statusElement.textContent = connectionStatus.charAt(0).toUpperCase() + connectionStatus.slice(1);
2978
- statusElement.className = `status ${connectionStatus.toLowerCase()}`;
2979
- }
2980
-
2981
- updateButtonStates(options = {}) {
2982
- const connectBtn = document.getElementById('connect-btn');
2983
- const disconnectBtn = document.getElementById('disconnect-btn');
2984
- const cleanupBtn = document.getElementById('cleanup-btn');
2985
- const healthCheckBtn = document.getElementById('health-check-btn');
2986
-
2987
- const isConnected = this.mesh.connected;
2988
- const isConnecting = options.connecting || false;
2989
- const isDisconnecting = options.disconnecting || false;
2990
-
2991
- if (connectBtn) {
2992
- connectBtn.disabled = isConnected || isConnecting;
2993
- connectBtn.textContent = isConnecting ? 'Connecting...' : 'Connect';
2994
- }
2995
-
2996
- if (disconnectBtn) {
2997
- disconnectBtn.disabled = !isConnected || isDisconnecting;
2998
- disconnectBtn.textContent = isDisconnecting ? 'Disconnecting...' : 'Disconnect';
2999
- }
3000
-
3001
- if (cleanupBtn) {
3002
- cleanupBtn.disabled = !isConnected;
3003
- }
3004
-
3005
- if (healthCheckBtn) {
3006
- healthCheckBtn.disabled = !isConnected;
3007
- }
3008
- }
3009
-
3010
- updateConnectedPeers() {
3011
- const peersList = document.getElementById('peers-list');
3012
- const connectedPeersCount = document.getElementById('connected-peers-count');
3013
-
3014
- if (!peersList || !connectedPeersCount) return;
3015
-
3016
- const peers = this.mesh.getPeers();
3017
- connectedPeersCount.textContent = peers.length;
3018
-
3019
- if (peers.length === 0) {
3020
- peersList.innerHTML = '<p class="empty-state">No peers connected</p>';
3021
- return;
3022
- }
3023
-
3024
- peersList.innerHTML = peers.map(peer => {
3025
- // peer is a plain object: { peerId, status, isInitiator, connectionStartTime }
3026
- const statusClass = peer.status === 'connected' ? 'connected' : 'connecting';
3027
- const connectionTime = ((Date.now() - peer.connectionStartTime) / 1000).toFixed(1);
3028
-
3029
- return `
3030
- <div class="peer-item">
3031
- <div class="peer-info">
3032
- <span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
3033
- <span class="peer-status ${statusClass}">${peer.status}</span>
3034
- </div>
3035
- <div class="peer-details">
3036
- <small>Connected: ${connectionTime}s ago</small>
3037
- <small>Role: ${peer.isInitiator ? 'Initiator' : 'Receiver'}</small>
3038
- </div>
3039
- </div>
3040
- `;
3041
- }).join('');
3042
- }
3043
-
3044
- updateDiscoveredPeers() {
3045
- const discoveredPeersList = document.getElementById('discovered-peers-list');
3046
- const discoveredPeersCount = document.getElementById('discovered-peers-count');
3047
-
3048
- if (!discoveredPeersList || !discoveredPeersCount) return;
3049
-
3050
- const discoveredPeers = this.mesh.getDiscoveredPeers();
3051
- const connectedPeerIds = this.mesh.getPeers().map(p => p.peerId);
3052
-
3053
- // Filter out already connected peers
3054
- const availablePeers = discoveredPeers.filter(peer =>
3055
- !connectedPeerIds.includes(peer.peerId) && peer.peerId !== this.mesh.peerId
3056
- );
3057
-
3058
- discoveredPeersCount.textContent = availablePeers.length;
3059
-
3060
- if (availablePeers.length === 0) {
3061
- discoveredPeersList.innerHTML = '<p class="empty-state">No peers discovered</p>';
3062
- return;
3063
- }
3064
-
3065
- discoveredPeersList.innerHTML = availablePeers.map(peer => {
3066
- const lastSeen = peer.lastSeen
3067
- ? `${Math.round((Date.now() - peer.lastSeen) / 1000)}s ago`
3068
- : 'Unknown';
3069
-
3070
- return `
3071
- <div class="peer-item discovered">
3072
- <div class="peer-info">
3073
- <span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
3074
- <button class="btn small" data-peer-id="${peer.peerId}" onclick="window.peerPigeonUI.connectToPeerFromButton(this)">
3075
- Connect
3076
- </button>
3077
- </div>
3078
- <div class="peer-details">
3079
- <small>Last seen: ${lastSeen}</small>
3080
- <small>Distance: ${peer.distance || 'Unknown'}</small>
3081
- </div>
3082
- </div>
3083
- `;
3084
- }).join('');
3085
- }
3086
-
3087
- updateSettings() {
3088
- // Update form values to match mesh state
3089
- const minPeersInput = document.getElementById('min-peers');
3090
- const maxPeersInput = document.getElementById('max-peers');
3091
- const autoDiscoveryToggle = document.getElementById('auto-discovery-toggle');
3092
- const evictionStrategyToggle = document.getElementById('eviction-strategy-toggle');
3093
- const xorRoutingToggle = document.getElementById('xor-routing-toggle');
3094
- const webdhtToggle = document.getElementById('webdht-toggle');
3095
-
3096
- if (minPeersInput) minPeersInput.value = this.mesh.minPeers;
3097
- if (maxPeersInput) maxPeersInput.value = this.mesh.maxPeers;
3098
- if (autoDiscoveryToggle) autoDiscoveryToggle.checked = this.mesh.autoDiscovery;
3099
- if (evictionStrategyToggle) evictionStrategyToggle.checked = this.mesh.evictionStrategy;
3100
- if (xorRoutingToggle) xorRoutingToggle.checked = this.mesh.xorRouting;
3101
-
3102
- // Update WebDHT status (read-only)
3103
- if (webdhtToggle) {
3104
- const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
3105
- webdhtToggle.checked = isDHTEnabled;
3106
-
3107
- // Update the visual styling based on status
3108
- const parent = webdhtToggle.closest('.auto-discovery-control');
3109
- if (parent) {
3110
- if (isDHTEnabled) {
3111
- parent.style.opacity = '1';
3112
- parent.title = 'WebDHT is enabled and running';
3113
- } else {
3114
- parent.style.opacity = '0.6';
3115
- parent.title = 'WebDHT is disabled (restart required to enable)';
3116
- }
3117
- }
3118
- }
3119
- }
3120
-
3121
- /**
3122
- * Add a message to the UI message log
3123
- * @param {string} sender - Message sender identifier
3124
- * @param {string} content - Message content
3125
- * @param {string} type - Message type ('info', 'error', 'warning', 'own', 'dm')
3126
- */
3127
- addMessage(sender, content, type = 'info') {
3128
- // System messages go to the system-messages container (below connection buttons)
3129
- // Chat messages go to the messages-log container (at the bottom)
3130
- if (sender === 'System') {
3131
- this.addSystemMessage(content, type);
3132
- } else {
3133
- this.addChatMessage(sender, content, type);
3134
- }
3135
- }
3136
-
3137
- /**
3138
- * Add a system message to the system messages container below connection buttons
3139
- * @param {string} content - Message content
3140
- * @param {string} type - Message type ('info', 'error', 'warning')
3141
- */
3142
- addSystemMessage(content, type = 'info') {
3143
- const systemMessages = document.getElementById('system-messages');
3144
- if (!systemMessages) return;
3145
-
3146
- const messageElement = document.createElement('div');
3147
- messageElement.className = `system-message ${type}`;
3148
-
3149
- const timestamp = new Date().toLocaleTimeString();
3150
-
3151
- messageElement.innerHTML = `
3152
- <div class="system-message-header">
3153
- <span class="system-message-time">${timestamp}</span>
3154
- <span class="system-message-type">${type.toUpperCase()}</span>
3155
- </div>
3156
- <div class="system-message-content">${content}</div>
3157
- `;
3158
-
3159
- systemMessages.appendChild(messageElement);
3160
- systemMessages.scrollTop = systemMessages.scrollHeight;
3161
-
3162
- // Limit message history to prevent memory issues
3163
- const messages = systemMessages.children;
3164
- if (messages.length > 50) {
3165
- systemMessages.removeChild(messages[0]);
3166
- }
3167
- }
3168
-
3169
- /**
3170
- * Add a chat message to the messages log at the bottom
3171
- * @param {string} sender - Message sender identifier
3172
- * @param {string} content - Message content
3173
- * @param {string} type - Message type ('own', 'dm', 'encrypted')
3174
- */
3175
- addChatMessage(sender, content, type = 'info') {
3176
- const messagesLog = document.getElementById('messages-log');
3177
- if (!messagesLog) return;
3178
-
3179
- const messageElement = document.createElement('div');
3180
- // Add 'encrypted' class if message type is 'encrypted'
3181
- const classes = `message-item ${type}`;
3182
- messageElement.className = classes;
3183
-
3184
- const timestamp = new Date().toLocaleTimeString();
3185
- const senderDisplay = sender === 'You' ? 'You' : sender.substring(0, 3);
3186
-
3187
- messageElement.innerHTML = `
3188
- <div class="avatar">${senderDisplay}</div>
3189
- <div class="message-body">
3190
- <div class="message-header">
3191
- ${sender} • ${timestamp}
3192
- </div>
3193
- <div class="message-content">${content}</div>
3194
- </div>
3195
- `;
3196
-
3197
- messagesLog.appendChild(messageElement);
3198
- messagesLog.scrollTop = messagesLog.scrollHeight;
3199
-
3200
- // Limit message history to prevent memory issues
3201
- const messages = messagesLog.children;
3202
- if (messages.length > 100) {
3203
- messagesLog.removeChild(messages[0]);
3204
- }
3205
- }
3206
-
3207
- /**
3208
- * Add an entry to the DHT log
3209
- * @param {string} message - The log message
3210
- */
3211
- addDHTLogEntry(message) {
3212
- const dhtLog = document.getElementById('dht-log');
3213
- if (!dhtLog) return;
3214
-
3215
- const logEntry = document.createElement('div');
3216
- logEntry.className = 'dht-log-entry';
3217
-
3218
- const timestamp = new Date().toLocaleTimeString();
3219
- logEntry.innerHTML = `
3220
- <span class="dht-log-time">${timestamp}</span>
3221
- <span class="dht-log-message">${message}</span>
3222
- `;
3223
-
3224
- dhtLog.appendChild(logEntry);
3225
- dhtLog.scrollTop = dhtLog.scrollHeight;
3226
-
3227
- // Limit log entries to prevent memory issues
3228
- const entries = dhtLog.children;
3229
- if (entries.length > 100) {
3230
- dhtLog.removeChild(entries[0]);
3231
- }
3232
- }
3233
-
3234
- /**
3235
- * Update the DHT status display
3236
- */
3237
- updateDHTStatus() {
3238
- const dhtStatusElement = document.getElementById('dht-status');
3239
- if (!dhtStatusElement) return;
3240
-
3241
- const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
3242
- dhtStatusElement.textContent = isDHTEnabled ? 'Enabled' : 'Disabled';
3243
- dhtStatusElement.className = `status ${isDHTEnabled ? 'connected' : 'disconnected'}`;
3244
- }
3245
-
3246
- // Crypto Helper Methods
3247
- // =====================
3248
-
3249
- /**
3250
- * Update the crypto status display
3251
- */
3252
- updateCryptoStatus() {
3253
- // Update main crypto status
3254
- const statusElement = document.getElementById('crypto-status');
3255
- if (statusElement) {
3256
- const status = this.mesh.getCryptoStatus();
3257
- statusElement.textContent = status.enabled ? 'Enabled' : 'Disabled';
3258
- statusElement.className = `status ${status.enabled ? 'enabled' : 'disabled'}`;
3259
- }
3260
-
3261
- // Update public key display
3262
- const publicKeyElement = document.getElementById('crypto-public-key');
3263
- if (publicKeyElement) {
3264
- const status = this.mesh.getCryptoStatus();
3265
- if (status.enabled && status.publicKey) {
3266
- publicKeyElement.textContent = status.publicKey.substring(0, 40) + '...';
3267
- publicKeyElement.title = status.publicKey; // Full key in tooltip
3268
- } else {
3269
- publicKeyElement.textContent = 'None';
3270
- publicKeyElement.title = '';
3271
- }
3272
- }
3273
-
3274
- // Update peer keys count
3275
- const peerCountElement = document.getElementById('crypto-peer-count');
3276
- if (peerCountElement) {
3277
- const status = this.mesh.getCryptoStatus();
3278
- const count = status.peerKeys ? Object.keys(status.peerKeys).length : 0;
3279
- peerCountElement.textContent = count.toString();
3280
- }
3281
-
3282
- // Update performance statistics
3283
- this.updateCryptoStats();
3284
- }
3285
-
3286
- /**
3287
- * Update crypto performance statistics
3288
- */
3289
- updateCryptoStats() {
3290
- const status = this.mesh.getCryptoStatus();
3291
- if (!status.performance) return;
3292
-
3293
- const stats = status.performance;
3294
-
3295
- // Update stat elements
3296
- const updateStat = (id, value) => {
3297
- const element = document.getElementById(id);
3298
- if (element) element.textContent = value.toString();
3299
- };
3300
-
3301
- updateStat('crypto-stats-encrypted', stats.messagesEncrypted || 0);
3302
- updateStat('crypto-stats-decrypted', stats.messagesDecrypted || 0);
3303
- updateStat('crypto-stats-encrypt-time', `${(stats.avgEncryptTime || 0).toFixed(2)}ms`);
3304
- updateStat('crypto-stats-decrypt-time', `${(stats.avgDecryptTime || 0).toFixed(2)}ms`);
3305
- updateStat('crypto-stats-key-exchanges', stats.keyExchanges || 0);
3306
- }
3307
-
3308
- /**
3309
- * Add a crypto test result to the test log
3310
- */
3311
- addCryptoTestResult(message, type = 'info') {
3312
- const testLog = document.getElementById('crypto-test-log');
3313
- if (!testLog) return;
3314
-
3315
- // Remove empty state message
3316
- const emptyState = testLog.querySelector('.empty-state');
3317
- if (emptyState) {
3318
- emptyState.remove();
3319
- }
3320
-
3321
- const logEntry = document.createElement('div');
3322
- logEntry.className = `test-result ${type}`;
3323
-
3324
- const timestamp = new Date().toLocaleTimeString();
3325
- logEntry.innerHTML = `
3326
- <span class="test-time">${timestamp}</span>
3327
- <span class="test-message">${message}</span>
3328
- `;
3329
-
3330
- testLog.appendChild(logEntry);
3331
- testLog.scrollTop = testLog.scrollHeight;
3332
-
3333
- // Limit log entries to prevent memory issues
3334
- const entries = testLog.querySelectorAll('.test-result');
3335
- if (entries.length > 50) {
3336
- entries[0].remove();
3337
- }
3338
- }
3339
-
3340
- /**
3341
- * Clear all crypto test results
3342
- */
3343
- clearCryptoTestResults() {
3344
- const testLog = document.getElementById('crypto-test-log');
3345
- if (!testLog) return;
3346
-
3347
- testLog.innerHTML = '<p class="empty-state">No tests run yet</p>';
3348
- }
3349
-
3350
- /**
3351
- * Update the group select dropdown
3352
- */
3353
- updateGroupSelect() {
3354
- const groupSelect = document.getElementById('crypto-group-select');
3355
- const groupsList = document.getElementById('crypto-groups-list');
3356
- if (!groupSelect || !groupsList) return;
3357
-
3358
- const status = this.mesh.getCryptoStatus();
3359
- const groups = status.groups || {};
3360
-
3361
- // Clear existing options (except placeholder)
3362
- const placeholder = groupSelect.querySelector('option[value=""]');
3363
- groupSelect.innerHTML = '';
3364
- if (placeholder) groupSelect.appendChild(placeholder);
3365
-
3366
- // Add group options
3367
- Object.keys(groups).forEach(groupId => {
3368
- const option = document.createElement('option');
3369
- option.value = groupId;
3370
- option.textContent = groupId;
3371
- groupSelect.appendChild(option);
3372
- });
3373
-
3374
- // Update groups list display
3375
- const groupCount = Object.keys(groups).length;
3376
- if (groupCount === 0) {
3377
- groupsList.innerHTML = '<h4>Active Groups:</h4><div class="empty-state">No groups created</div>';
3378
- } else {
3379
- let html = '<h4>Active Groups:</h4>';
3380
- Object.entries(groups).forEach(([groupId, groupInfo]) => {
3381
- html += `
3382
- <div class="group-item">
3383
- <strong>${groupId}</strong>
3384
- <small>Created: ${new Date(groupInfo.created).toLocaleString()}</small>
3385
- </div>
3386
- `;
3387
- });
3388
- groupsList.innerHTML = html;
3389
- }
3390
- }
3391
- }