peerpigeon 0.1.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -1365
- package/cli.js +1382 -0
- package/dist/peerpigeon-browser.js +12450 -0
- package/dist/peerpigeon-browser.js.map +7 -0
- package/docs/API_DOCUMENTATION.md +1976 -0
- package/docs/BOOTSTRAP_HUBS.md +319 -0
- package/docs/CLI_README.md +371 -0
- package/docs/CUSTOM_HUB_NAMESPACES.md +182 -0
- package/docs/CUSTOM_NAMESPACE_IMPLEMENTATION.md +187 -0
- package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
- package/docs/HUB_QUICK_REF.md +108 -0
- package/docs/HUB_SCRIPTS.md +341 -0
- package/docs/HUB_SYSTEM.md +599 -0
- package/docs/MIGRATION_COMPLETE.md +93 -0
- package/docs/NETWORK_NAMESPACES.md +212 -0
- package/docs/PIGEONRTC_MIGRATION.md +280 -0
- package/docs/README.md +108 -0
- package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
- package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
- package/examples/bootstrap-hub-example.js +292 -0
- package/examples/browser/README.md +278 -0
- package/examples/browser/app.js +2426 -49
- package/examples/browser/index.html +481 -630
- package/examples/browser/minimal/README.md +55 -0
- package/examples/browser/minimal/index.html +75 -0
- package/examples/browser/minimal/minimal.js +234 -0
- package/examples/browser/styles.css +687 -1425
- package/examples/browser/test-bundle.html +35 -0
- package/examples/browser-2/index.html +30 -0
- package/examples/browser-2/package.json +21 -0
- package/examples/browser-2/src/App-simple.vue +21 -0
- package/examples/browser-2/src/App.vue +420 -0
- package/examples/browser-2/src/components/CryptoView.vue +1661 -0
- package/examples/browser-2/src/components/DHTView.vue +1281 -0
- package/examples/browser-2/src/components/DebugView.vue +1773 -0
- package/examples/browser-2/src/components/MediaView.vue +1048 -0
- package/examples/browser-2/src/components/MessagingView.vue +775 -0
- package/examples/browser-2/src/components/NetworkView.vue +930 -0
- package/examples/browser-2/src/components/StorageView.vue +1376 -0
- package/examples/browser-2/src/main.js +5 -0
- package/examples/browser-2/src/stores/peerpigeon.js +895 -0
- package/examples/browser-2/vite.config.js +6 -0
- package/examples/hub-example.js +189 -0
- package/examples/multi-hub-test.js +186 -0
- package/examples/node/README.md +2 -2
- package/examples/programmatic-namespace-example.js +108 -0
- package/examples/selective-streaming-demo.html +698 -0
- package/examples/standard-events-demo.js +126 -0
- package/index.js +7 -1
- package/package.json +34 -16
- package/server/index.js +1058 -98
- package/server/start.js +52 -0
- package/src/ConnectionManager.js +239 -225
- package/src/CryptoManager.js +147 -18
- package/src/DebugLogger.js +0 -7
- package/src/DistributedStorageManager.js +224 -205
- package/src/EnvironmentDetector.js +88 -4
- package/src/EventEmitter.js +79 -1
- package/src/EvictionManager.js +10 -9
- package/src/GossipManager.js +163 -11
- package/src/MediaManager.js +12 -2
- package/src/PeerConnection.js +343 -311
- package/src/PeerPigeonMesh.js +576 -135
- package/src/PigeonRTC-browser.js +247 -0
- package/src/SignalingClient.js +14 -243
- package/src/SignalingHandler.js +31 -10
- package/src/StorageManager.js +0 -39
- package/src/WebDHT-Simple.js +389 -0
- package/src/WebDHT.js +363 -1165
- package/src/browser-entry.js +58 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/crypto-test.html +0 -427
- package/examples/browser/ui-old.js +0 -1926
- package/examples/browser/ui.js +0 -3391
- package/websocket-server/README.md +0 -247
- package/websocket-server/server.js +0 -391
package/src/PeerConnection.js
CHANGED
|
@@ -14,10 +14,8 @@ export class PeerConnection extends EventEmitter {
|
|
|
14
14
|
this.dataChannelReady = false;
|
|
15
15
|
this.connectionStartTime = Date.now();
|
|
16
16
|
this.pendingIceCandidates = [];
|
|
17
|
-
this.iceCheckingTimeout = null; // Timeout for ICE checking state
|
|
18
|
-
this.connectingTimeout = null; // Timeout for stuck connecting state
|
|
19
|
-
this.dataChannelHealthMonitor = null; // Health monitoring for data channel when signaling is unavailable
|
|
20
17
|
this.isClosing = false; // Flag to prevent disconnection events during intentional close
|
|
18
|
+
this.iceTimeoutId = null; // Timeout ID for ICE negotiation
|
|
21
19
|
this._forcedStatus = null; // Track forced status (e.g., failed)
|
|
22
20
|
|
|
23
21
|
// Media stream support
|
|
@@ -27,6 +25,10 @@ export class PeerConnection extends EventEmitter {
|
|
|
27
25
|
this.enableAudio = options.enableAudio || false;
|
|
28
26
|
this.audioTransceiver = null;
|
|
29
27
|
this.videoTransceiver = null;
|
|
28
|
+
|
|
29
|
+
// SECURITY: Never automatically invoke remote streams - only when user explicitly requests
|
|
30
|
+
this.allowRemoteStreams = options.allowRemoteStreams === true; // Default to false - streams must be explicitly invoked
|
|
31
|
+
this.pendingRemoteStreams = []; // Buffer remote streams until user invokes them
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
/**
|
|
@@ -47,43 +49,50 @@ export class PeerConnection extends EventEmitter {
|
|
|
47
49
|
throw error;
|
|
48
50
|
}
|
|
49
51
|
|
|
50
|
-
|
|
52
|
+
// Get PigeonRTC instance for cross-platform WebRTC support
|
|
53
|
+
const pigeonRTC = environmentDetector.getPigeonRTC();
|
|
54
|
+
if (!pigeonRTC) {
|
|
55
|
+
const error = new Error('PigeonRTC not initialized - call initWebRTCAsync() first');
|
|
56
|
+
this.emit('connectionFailed', { peerId: this.peerId, reason: error.message });
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Create peer connection using PigeonRTC
|
|
61
|
+
this.connection = pigeonRTC.createPeerConnection({
|
|
51
62
|
iceServers: [
|
|
52
63
|
{ urls: 'stun:stun.l.google.com:19302' },
|
|
53
|
-
{ urls: 'stun:stun1.l.google.com:19302' }
|
|
54
|
-
|
|
64
|
+
{ urls: 'stun:stun1.l.google.com:19302' },
|
|
65
|
+
{ urls: 'stun:stun2.l.google.com:19302' },
|
|
66
|
+
{ urls: 'stun:stun3.l.google.com:19302' },
|
|
67
|
+
{ urls: 'stun:stun4.l.google.com:19302' }
|
|
68
|
+
],
|
|
69
|
+
iceCandidatePoolSize: 10, // Pre-gather ICE candidates for faster connection
|
|
70
|
+
bundlePolicy: 'max-bundle', // Bundle all media on single transport for efficiency
|
|
71
|
+
rtcpMuxPolicy: 'require' // Multiplex RTP and RTCP for faster setup
|
|
55
72
|
});
|
|
56
73
|
|
|
57
74
|
this.setupConnectionHandlers();
|
|
58
75
|
|
|
59
|
-
//
|
|
60
|
-
// This ensures
|
|
61
|
-
this.debug.log('🔄
|
|
62
|
-
|
|
63
|
-
// Always add audio transceiver
|
|
64
|
-
this.audioTransceiver = this.connection.addTransceiver('audio', {
|
|
65
|
-
direction: 'sendrecv'
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
// Always add video transceiver
|
|
69
|
-
this.videoTransceiver = this.connection.addTransceiver('video', {
|
|
70
|
-
direction: 'sendrecv'
|
|
71
|
-
});
|
|
76
|
+
// CRITICAL FIX: Use addTrack() instead of pre-allocated transceivers to trigger ontrack events
|
|
77
|
+
// This ensures that ontrack events are properly fired on the receiving side
|
|
78
|
+
this.debug.log('🔄 Using addTrack() approach for proper ontrack event firing');
|
|
72
79
|
|
|
73
|
-
// Add local media stream if provided
|
|
80
|
+
// Add local media stream if provided using addTrack()
|
|
74
81
|
if (this.localStream) {
|
|
75
|
-
this.debug.log('Adding local stream tracks
|
|
76
|
-
await this.
|
|
82
|
+
this.debug.log('Adding local stream tracks using addTrack() method');
|
|
83
|
+
await this.addLocalStreamWithAddTrack(this.localStream);
|
|
77
84
|
}
|
|
78
85
|
|
|
79
86
|
if (this.isInitiator) {
|
|
87
|
+
this.debug.log(`🚀 INITIATOR: Creating data channel for ${this.peerId.substring(0, 8)}... (WE are initiator)`);
|
|
80
88
|
this.dataChannel = this.connection.createDataChannel('messages', {
|
|
81
89
|
ordered: true
|
|
82
90
|
});
|
|
83
91
|
this.setupDataChannel();
|
|
84
92
|
} else {
|
|
93
|
+
this.debug.log(`👥 RECEIVER: Waiting for data channel from ${this.peerId.substring(0, 8)}... (THEY are initiator)`);
|
|
85
94
|
this.connection.ondatachannel = (event) => {
|
|
86
|
-
this.debug.log(
|
|
95
|
+
this.debug.log(`📨 RECEIVED: Data channel received from ${this.peerId.substring(0, 8)}...`);
|
|
87
96
|
this.dataChannel = event.channel;
|
|
88
97
|
this.setupDataChannel();
|
|
89
98
|
};
|
|
@@ -139,8 +148,16 @@ export class PeerConnection extends EventEmitter {
|
|
|
139
148
|
});
|
|
140
149
|
|
|
141
150
|
this.debug.log('🚨 ONTRACK DEBUG: About to emit remoteStream event');
|
|
142
|
-
|
|
143
|
-
|
|
151
|
+
|
|
152
|
+
// Check if remote streams are allowed (crypto gating)
|
|
153
|
+
if (this.allowRemoteStreams) {
|
|
154
|
+
this.emit('remoteStream', { peerId: this.peerId, stream: this.remoteStream });
|
|
155
|
+
this.debug.log('✅ ONTRACK DEBUG: remoteStream event emitted successfully');
|
|
156
|
+
} else {
|
|
157
|
+
// Buffer the stream until crypto allows it
|
|
158
|
+
this.debug.log('🔒 ONTRACK DEBUG: Buffering remote stream until crypto verification');
|
|
159
|
+
this.pendingRemoteStreams.push({ peerId: this.peerId, stream: this.remoteStream });
|
|
160
|
+
}
|
|
144
161
|
} else {
|
|
145
162
|
this.debug.error('❌ ONTRACK DEBUG: No stream in ontrack event - this should not happen');
|
|
146
163
|
}
|
|
@@ -161,36 +178,26 @@ export class PeerConnection extends EventEmitter {
|
|
|
161
178
|
}
|
|
162
179
|
|
|
163
180
|
if (this.connection.connectionState === 'connected') {
|
|
164
|
-
// Clear any pending timeouts
|
|
165
|
-
if (this.connectingTimeout) {
|
|
166
|
-
clearTimeout(this.connectingTimeout);
|
|
167
|
-
this.connectingTimeout = null;
|
|
168
|
-
}
|
|
169
181
|
this.debug.log(`✅ Connection established with ${this.peerId}`);
|
|
170
182
|
this.emit('connected', { peerId: this.peerId });
|
|
171
183
|
} else if (this.connection.connectionState === 'connecting') {
|
|
172
184
|
this.debug.log(`🔄 Connection to ${this.peerId} is connecting...`);
|
|
173
|
-
// Add timeout for stuck connecting state
|
|
174
|
-
if (this.connectingTimeout) {
|
|
175
|
-
clearTimeout(this.connectingTimeout);
|
|
176
|
-
}
|
|
177
|
-
this.connectingTimeout = setTimeout(() => {
|
|
178
|
-
if (this.connection && this.connection.connectionState === 'connecting' && !this.isClosing) {
|
|
179
|
-
this.debug.log(`⏰ Connection stuck in connecting state for ${this.peerId}, treating as failed`);
|
|
180
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'connection timeout' });
|
|
181
|
-
}
|
|
182
|
-
}, 20000); // Increased timeout to 20 seconds for better stability
|
|
183
185
|
} else if (this.connection.connectionState === 'disconnected') {
|
|
184
186
|
// Give WebRTC more time to recover - it's common for connections to briefly disconnect during renegotiation
|
|
185
187
|
this.debug.log(`⚠️ WebRTC connection disconnected for ${this.peerId}, waiting for potential recovery...`);
|
|
188
|
+
|
|
189
|
+
// Longer recovery time for disconnected state when there are multiple peers (3+)
|
|
190
|
+
// This helps prevent cascade failures when multiple renegotiations happen
|
|
191
|
+
const recoveryTime = 12000; // 12 seconds for disconnected state recovery
|
|
192
|
+
|
|
186
193
|
setTimeout(() => {
|
|
187
194
|
if (this.connection &&
|
|
188
195
|
this.connection.connectionState === 'disconnected' &&
|
|
189
196
|
!this.isClosing) {
|
|
190
|
-
this.debug.log(`❌ WebRTC connection remained disconnected for ${this.peerId}, treating as failed`);
|
|
197
|
+
this.debug.log(`❌ WebRTC connection remained disconnected for ${this.peerId} after ${recoveryTime}ms, treating as failed`);
|
|
191
198
|
this.emit('disconnected', { peerId: this.peerId, reason: 'connection disconnected' });
|
|
192
199
|
}
|
|
193
|
-
},
|
|
200
|
+
}, recoveryTime);
|
|
194
201
|
} else if (this.connection.connectionState === 'failed') {
|
|
195
202
|
if (!this.isClosing) {
|
|
196
203
|
this.debug.log(`❌ Connection failed for ${this.peerId}`);
|
|
@@ -208,41 +215,25 @@ export class PeerConnection extends EventEmitter {
|
|
|
208
215
|
this.debug.log(`🧊 ICE connection state with ${this.peerId}: ${this.connection.iceConnectionState}`);
|
|
209
216
|
|
|
210
217
|
if (this.connection.iceConnectionState === 'connected') {
|
|
211
|
-
// Clear any pending timeout
|
|
212
|
-
if (this.iceCheckingTimeout) {
|
|
213
|
-
clearTimeout(this.iceCheckingTimeout);
|
|
214
|
-
this.iceCheckingTimeout = null;
|
|
215
|
-
}
|
|
216
218
|
this.debug.log(`✅ ICE connection established with ${this.peerId}`);
|
|
219
|
+
// Clear any existing ICE timeout
|
|
220
|
+
if (this.iceTimeoutId) {
|
|
221
|
+
clearTimeout(this.iceTimeoutId);
|
|
222
|
+
this.iceTimeoutId = null;
|
|
223
|
+
}
|
|
217
224
|
} else if (this.connection.iceConnectionState === 'checking') {
|
|
218
225
|
this.debug.log(`🔄 ICE checking for ${this.peerId}...`);
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
226
|
+
|
|
227
|
+
// Set a timeout for ICE negotiation to prevent hanging
|
|
228
|
+
if (this.iceTimeoutId) {
|
|
229
|
+
clearTimeout(this.iceTimeoutId);
|
|
222
230
|
}
|
|
223
|
-
this.
|
|
224
|
-
if (this.connection && this.connection.iceConnectionState === 'checking') {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
|
|
228
|
-
|
|
229
|
-
if (hasSignaling || hasMeshConnectivity) {
|
|
230
|
-
this.debug.log(`⏰ ICE checking timeout for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
|
|
231
|
-
try {
|
|
232
|
-
this.restartIceViaSignaling().catch(error => {
|
|
233
|
-
this.debug.error('Failed to restart ICE:', error);
|
|
234
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE restart failed' });
|
|
235
|
-
});
|
|
236
|
-
} catch (error) {
|
|
237
|
-
this.debug.error('Failed to restart ICE:', error);
|
|
238
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE restart failed' });
|
|
239
|
-
}
|
|
240
|
-
} else {
|
|
241
|
-
this.debug.log(`⏰ ICE checking timeout for ${this.peerId}, but no signaling available - keeping connection alive`);
|
|
242
|
-
// Don't disconnect - peer connection may still work without signaling server
|
|
243
|
-
}
|
|
231
|
+
this.iceTimeoutId = setTimeout(() => {
|
|
232
|
+
if (this.connection && this.connection.iceConnectionState === 'checking' && !this.isClosing) {
|
|
233
|
+
this.debug.error(`❌ ICE negotiation timeout for ${this.peerId} - connection stuck in checking state`);
|
|
234
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE negotiation timeout' });
|
|
244
235
|
}
|
|
245
|
-
}, 30000); //
|
|
236
|
+
}, 30000); // 30 second timeout for ICE negotiation
|
|
246
237
|
} else if (this.connection.iceConnectionState === 'failed') {
|
|
247
238
|
// Check if signaling is available before attempting ICE restart
|
|
248
239
|
const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
|
|
@@ -261,9 +252,8 @@ export class PeerConnection extends EventEmitter {
|
|
|
261
252
|
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE failed' });
|
|
262
253
|
}
|
|
263
254
|
} else {
|
|
264
|
-
this.debug.log(`❌ ICE connection failed for ${this.peerId},
|
|
265
|
-
|
|
266
|
-
this.monitorDataChannelHealth();
|
|
255
|
+
this.debug.log(`❌ ICE connection failed for ${this.peerId}, disconnecting`);
|
|
256
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE failed' });
|
|
267
257
|
}
|
|
268
258
|
} else if (this.connection.iceConnectionState === 'disconnected') {
|
|
269
259
|
// Give more time for ICE reconnection - this is common during renegotiation
|
|
@@ -288,12 +278,11 @@ export class PeerConnection extends EventEmitter {
|
|
|
288
278
|
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
289
279
|
}
|
|
290
280
|
} else {
|
|
291
|
-
this.debug.log(`❌ ICE remained disconnected for ${this.peerId},
|
|
292
|
-
|
|
293
|
-
this.monitorDataChannelHealth();
|
|
281
|
+
this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, disconnecting`);
|
|
282
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
294
283
|
}
|
|
295
284
|
}
|
|
296
|
-
},
|
|
285
|
+
}, 5000); // Faster ICE reconnection - 5 seconds
|
|
297
286
|
}
|
|
298
287
|
};
|
|
299
288
|
|
|
@@ -355,30 +344,6 @@ export class PeerConnection extends EventEmitter {
|
|
|
355
344
|
this.dataChannel.onmessage = (event) => {
|
|
356
345
|
try {
|
|
357
346
|
const message = JSON.parse(event.data);
|
|
358
|
-
|
|
359
|
-
// Handle internal ping messages for health monitoring
|
|
360
|
-
if (message.type === 'ping') {
|
|
361
|
-
this.debug.log(`📡 Received health ping from ${this.peerId}, responding with pong`);
|
|
362
|
-
try {
|
|
363
|
-
const pongMessage = {
|
|
364
|
-
type: 'pong',
|
|
365
|
-
timestamp: Date.now(),
|
|
366
|
-
originalTimestamp: message.timestamp,
|
|
367
|
-
from: this.mesh?.peerId || 'unknown'
|
|
368
|
-
};
|
|
369
|
-
this.dataChannel.send(JSON.stringify(pongMessage));
|
|
370
|
-
} catch (error) {
|
|
371
|
-
this.debug.error('Failed to send pong response:', error);
|
|
372
|
-
}
|
|
373
|
-
return; // Don't emit this as a regular message
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
// Handle pong responses (optional logging)
|
|
377
|
-
if (message.type === 'pong') {
|
|
378
|
-
this.debug.log(`📡 Received health pong from ${this.peerId}`);
|
|
379
|
-
return; // Don't emit this as a regular message
|
|
380
|
-
}
|
|
381
|
-
|
|
382
347
|
this.emit('message', { peerId: this.peerId, message });
|
|
383
348
|
} catch (error) {
|
|
384
349
|
this.debug.error('Failed to parse message:', error);
|
|
@@ -397,10 +362,59 @@ export class PeerConnection extends EventEmitter {
|
|
|
397
362
|
};
|
|
398
363
|
}
|
|
399
364
|
|
|
365
|
+
// CRITICAL: Check and force data channel state after answer processing
|
|
366
|
+
checkDataChannelState() {
|
|
367
|
+
if (this.dataChannel) {
|
|
368
|
+
this.debug.log(`🔍 DATA CHANNEL CHECK: State for ${this.peerId.substring(0, 8)}... is ${this.dataChannel.readyState}`);
|
|
369
|
+
|
|
370
|
+
// If data channel is open but we haven't triggered the open event yet
|
|
371
|
+
if (this.dataChannel.readyState === 'open' && !this.dataChannelReady) {
|
|
372
|
+
this.debug.log(`🚀 FORCE OPEN: Triggering data channel open for ${this.peerId.substring(0, 8)}...`);
|
|
373
|
+
this.dataChannelReady = true;
|
|
374
|
+
this.emit('dataChannelOpen', { peerId: this.peerId });
|
|
375
|
+
}
|
|
376
|
+
// If data channel is connecting, set up a check in case the event doesn't fire
|
|
377
|
+
else if (this.dataChannel.readyState === 'connecting') {
|
|
378
|
+
this.debug.log(`⏳ CONNECTING: Data channel connecting for ${this.peerId.substring(0, 8)}..., setting up backup check`);
|
|
379
|
+
setTimeout(() => {
|
|
380
|
+
if (this.dataChannel && this.dataChannel.readyState === 'open' && !this.dataChannelReady) {
|
|
381
|
+
this.debug.log(`🚀 BACKUP OPEN: Backup trigger for data channel open for ${this.peerId.substring(0, 8)}...`);
|
|
382
|
+
this.dataChannelReady = true;
|
|
383
|
+
this.emit('dataChannelOpen', { peerId: this.peerId });
|
|
384
|
+
}
|
|
385
|
+
}, 100); // Short delay to allow normal event to fire first
|
|
386
|
+
} else {
|
|
387
|
+
this.debug.log(`❌ DATA CHANNEL CHECK: No data channel found for ${this.peerId.substring(0, 8)}...`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
400
392
|
async createOffer() {
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
393
|
+
// Create offer with optimized settings for faster connection and timeout protection
|
|
394
|
+
try {
|
|
395
|
+
const offer = await Promise.race([
|
|
396
|
+
this.connection.createOffer({
|
|
397
|
+
offerToReceiveAudio: true,
|
|
398
|
+
offerToReceiveVideo: true,
|
|
399
|
+
iceRestart: false // Don't restart ICE unless necessary
|
|
400
|
+
}),
|
|
401
|
+
new Promise((resolve, reject) =>
|
|
402
|
+
setTimeout(() => reject(new Error('createOffer timeout')), 10000)
|
|
403
|
+
)
|
|
404
|
+
]);
|
|
405
|
+
|
|
406
|
+
await Promise.race([
|
|
407
|
+
this.connection.setLocalDescription(offer),
|
|
408
|
+
new Promise((resolve, reject) =>
|
|
409
|
+
setTimeout(() => reject(new Error('setLocalDescription timeout')), 10000)
|
|
410
|
+
)
|
|
411
|
+
]);
|
|
412
|
+
|
|
413
|
+
return offer;
|
|
414
|
+
} catch (error) {
|
|
415
|
+
this.debug.error(`❌ Failed to create offer for ${this.peerId}:`, error);
|
|
416
|
+
throw error;
|
|
417
|
+
}
|
|
404
418
|
}
|
|
405
419
|
|
|
406
420
|
async handleOffer(offer) {
|
|
@@ -442,16 +456,38 @@ export class PeerConnection extends EventEmitter {
|
|
|
442
456
|
this.debug.log(`🔄 OFFER DEBUG: State validation passed, processing offer from ${this.peerId.substring(0, 8)}... SDP length: ${offer.sdp.length}`);
|
|
443
457
|
|
|
444
458
|
try {
|
|
445
|
-
await
|
|
459
|
+
await Promise.race([
|
|
460
|
+
this.connection.setRemoteDescription(offer),
|
|
461
|
+
new Promise((resolve, reject) =>
|
|
462
|
+
setTimeout(() => reject(new Error('setRemoteDescription timeout')), 10000)
|
|
463
|
+
)
|
|
464
|
+
]);
|
|
465
|
+
|
|
446
466
|
this.remoteDescriptionSet = true;
|
|
447
467
|
this.debug.log(`✅ OFFER DEBUG: Offer processed successfully from ${this.peerId.substring(0, 8)}...`);
|
|
448
468
|
this.debug.log(`✅ OFFER DEBUG: New signaling state after offer: ${this.connection.signalingState}`);
|
|
449
469
|
await this.processPendingIceCandidates();
|
|
450
470
|
|
|
451
|
-
const answer = await
|
|
452
|
-
|
|
471
|
+
const answer = await Promise.race([
|
|
472
|
+
this.connection.createAnswer(),
|
|
473
|
+
new Promise((resolve, reject) =>
|
|
474
|
+
setTimeout(() => reject(new Error('createAnswer timeout')), 10000)
|
|
475
|
+
)
|
|
476
|
+
]);
|
|
477
|
+
|
|
478
|
+
await Promise.race([
|
|
479
|
+
this.connection.setLocalDescription(answer),
|
|
480
|
+
new Promise((resolve, reject) =>
|
|
481
|
+
setTimeout(() => reject(new Error('setLocalDescription timeout')), 10000)
|
|
482
|
+
)
|
|
483
|
+
]);
|
|
484
|
+
|
|
453
485
|
this.debug.log(`✅ OFFER DEBUG: Answer created for offer from ${this.peerId.substring(0, 8)}...`);
|
|
454
486
|
this.debug.log(`✅ OFFER DEBUG: Final signaling state after answer: ${this.connection.signalingState}`);
|
|
487
|
+
|
|
488
|
+
// CRITICAL: Force check data channel state after offer/answer processing
|
|
489
|
+
this.checkDataChannelState();
|
|
490
|
+
|
|
455
491
|
return answer;
|
|
456
492
|
} catch (error) {
|
|
457
493
|
this.debug.error(`❌ OFFER DEBUG: Failed to process offer from ${this.peerId}:`, error);
|
|
@@ -508,12 +544,21 @@ export class PeerConnection extends EventEmitter {
|
|
|
508
544
|
this.debug.log(`🔄 ANSWER DEBUG: State validation passed, processing answer from ${this.peerId.substring(0, 8)}... SDP length: ${answer.sdp.length}`);
|
|
509
545
|
|
|
510
546
|
try {
|
|
511
|
-
await
|
|
547
|
+
await Promise.race([
|
|
548
|
+
this.connection.setRemoteDescription(answer),
|
|
549
|
+
new Promise((resolve, reject) =>
|
|
550
|
+
setTimeout(() => reject(new Error('setRemoteDescription timeout')), 10000)
|
|
551
|
+
)
|
|
552
|
+
]);
|
|
553
|
+
|
|
512
554
|
this.remoteDescriptionSet = true;
|
|
513
555
|
this.debug.log(`✅ ANSWER DEBUG: Answer processed successfully from ${this.peerId.substring(0, 8)}...`);
|
|
514
556
|
this.debug.log(`✅ ANSWER DEBUG: New signaling state: ${this.connection.signalingState}`);
|
|
515
557
|
this.debug.log(`✅ ANSWER DEBUG: New connection state: ${this.connection.connectionState}`);
|
|
516
558
|
await this.processPendingIceCandidates();
|
|
559
|
+
|
|
560
|
+
// CRITICAL: Force check data channel state after answer processing
|
|
561
|
+
this.checkDataChannelState();
|
|
517
562
|
} catch (error) {
|
|
518
563
|
this.debug.error(`❌ ANSWER DEBUG: Failed to set remote description for answer from ${this.peerId}:`, error);
|
|
519
564
|
this.debug.error('ANSWER DEBUG: Answer SDP that failed:', answer.sdp);
|
|
@@ -549,7 +594,12 @@ export class PeerConnection extends EventEmitter {
|
|
|
549
594
|
}
|
|
550
595
|
|
|
551
596
|
try {
|
|
552
|
-
await
|
|
597
|
+
await Promise.race([
|
|
598
|
+
this.connection.addIceCandidate(candidate),
|
|
599
|
+
new Promise((resolve, reject) =>
|
|
600
|
+
setTimeout(() => reject(new Error('addIceCandidate timeout')), 5000)
|
|
601
|
+
)
|
|
602
|
+
]);
|
|
553
603
|
this.debug.log(`🧊 Successfully added ICE candidate for ${this.peerId.substring(0, 8)}...`);
|
|
554
604
|
} catch (error) {
|
|
555
605
|
this.debug.error(`🧊 Failed to add ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
|
|
@@ -566,7 +616,12 @@ export class PeerConnection extends EventEmitter {
|
|
|
566
616
|
|
|
567
617
|
for (const candidate of this.pendingIceCandidates) {
|
|
568
618
|
try {
|
|
569
|
-
await
|
|
619
|
+
await Promise.race([
|
|
620
|
+
this.connection.addIceCandidate(candidate),
|
|
621
|
+
new Promise((resolve, reject) =>
|
|
622
|
+
setTimeout(() => reject(new Error('addIceCandidate timeout')), 5000)
|
|
623
|
+
)
|
|
624
|
+
]);
|
|
570
625
|
this.debug.log(`🧊 Successfully added buffered ICE candidate (${candidate.type}) for ${this.peerId.substring(0, 8)}...`);
|
|
571
626
|
} catch (error) {
|
|
572
627
|
this.debug.error(`🧊 Failed to add buffered ICE candidate for ${this.peerId.substring(0, 8)}...:`, error);
|
|
@@ -626,7 +681,16 @@ export class PeerConnection extends EventEmitter {
|
|
|
626
681
|
this.processedTrackIds.add(track.id);
|
|
627
682
|
|
|
628
683
|
this.debug.log('🚨 TRACK CHECK: Emitting remoteStream event for new track');
|
|
629
|
-
|
|
684
|
+
|
|
685
|
+
// Check if remote streams are allowed (crypto gating)
|
|
686
|
+
if (this.allowRemoteStreams) {
|
|
687
|
+
this.emit('remoteStream', { peerId: this.peerId, stream: this.remoteStream });
|
|
688
|
+
} else {
|
|
689
|
+
// Buffer the stream until crypto allows it
|
|
690
|
+
this.debug.log('🔒 TRACK CHECK: Buffering remote stream until crypto verification');
|
|
691
|
+
this.pendingRemoteStreams.push({ peerId: this.peerId, stream: this.remoteStream });
|
|
692
|
+
}
|
|
693
|
+
|
|
630
694
|
foundNewTracks = true;
|
|
631
695
|
}
|
|
632
696
|
}
|
|
@@ -647,6 +711,16 @@ export class PeerConnection extends EventEmitter {
|
|
|
647
711
|
validateRemoteStream(stream, track) {
|
|
648
712
|
this.debug.log('🔍 VALIDATION: Starting remote stream validation...');
|
|
649
713
|
|
|
714
|
+
// Check 0: Ensure stream and track are valid
|
|
715
|
+
if (!stream) {
|
|
716
|
+
this.debug.error('❌ VALIDATION: Stream is null or undefined');
|
|
717
|
+
return false;
|
|
718
|
+
}
|
|
719
|
+
if (!track) {
|
|
720
|
+
this.debug.error('❌ VALIDATION: Track is null or undefined');
|
|
721
|
+
return false;
|
|
722
|
+
}
|
|
723
|
+
|
|
650
724
|
// Check 1: Stream ID collision (basic loopback detection)
|
|
651
725
|
if (this.localStream && stream.id === this.localStream.id) {
|
|
652
726
|
this.debug.error('❌ LOOPBACK DETECTED: Received our own local stream as remote!');
|
|
@@ -694,8 +768,8 @@ export class PeerConnection extends EventEmitter {
|
|
|
694
768
|
}
|
|
695
769
|
}
|
|
696
770
|
|
|
697
|
-
// Check 4: Verify stream hasn't been marked as local origin
|
|
698
|
-
if (stream._peerPigeonOrigin === 'local') {
|
|
771
|
+
// Check 4: Verify stream hasn't been marked as local origin (with safe property access)
|
|
772
|
+
if (stream && stream._peerPigeonOrigin === 'local') {
|
|
699
773
|
this.debug.error('❌ Stream marked as local origin - preventing synchronization loop');
|
|
700
774
|
return false;
|
|
701
775
|
}
|
|
@@ -744,129 +818,103 @@ export class PeerConnection extends EventEmitter {
|
|
|
744
818
|
}
|
|
745
819
|
|
|
746
820
|
/**
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
async
|
|
750
|
-
if (!this.connection)
|
|
751
|
-
throw new Error('Connection not initialized');
|
|
752
|
-
}
|
|
821
|
+
* Add local stream using addTrack() method to trigger ontrack events
|
|
822
|
+
*/
|
|
823
|
+
async addLocalStreamWithAddTrack(stream) {
|
|
824
|
+
if (!stream || !this.connection) return;
|
|
753
825
|
|
|
754
|
-
this.debug.log(
|
|
826
|
+
this.debug.log('🎥 Adding local stream using addTrack() for proper ontrack events');
|
|
755
827
|
|
|
756
|
-
|
|
757
|
-
const
|
|
758
|
-
this.debug.log('🔍 Current transceivers before stream change:', transceivers.map(t => ({
|
|
759
|
-
kind: t.receiver.track?.kind || 'unknown',
|
|
760
|
-
direction: t.direction,
|
|
761
|
-
hasTrack: !!t.sender.track,
|
|
762
|
-
mid: t.mid
|
|
763
|
-
})));
|
|
828
|
+
const audioTracks = stream.getAudioTracks();
|
|
829
|
+
const videoTracks = stream.getVideoTracks();
|
|
764
830
|
|
|
765
|
-
//
|
|
766
|
-
this.
|
|
831
|
+
// Mark stream as local origin to prevent loopback
|
|
832
|
+
this.markStreamAsLocal(stream);
|
|
767
833
|
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
this.audioTransceiver.direction = 'sendrecv';
|
|
781
|
-
|
|
782
|
-
// Setup audio sending monitoring
|
|
783
|
-
this.setupAudioSendingMonitoring(audioTracks[0]);
|
|
784
|
-
this.debug.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} - track enabled: ${audioTracks[0].enabled}`);
|
|
785
|
-
} else {
|
|
786
|
-
this.debug.log('🔄 Removing audio track from stored transceiver');
|
|
787
|
-
await this.audioTransceiver.sender.replaceTrack(null);
|
|
788
|
-
this.audioTransceiver.direction = 'recvonly';
|
|
789
|
-
this.debug.log(`🎤 STOPPED SENDING AUDIO to peer ${this.peerId.substring(0, 8)}`);
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
// Handle video track using stored reference
|
|
794
|
-
if (this.videoTransceiver) {
|
|
795
|
-
if (videoTracks.length > 0) {
|
|
796
|
-
this.debug.log('🔄 Replacing video track in stored transceiver');
|
|
797
|
-
await this.videoTransceiver.sender.replaceTrack(videoTracks[0]);
|
|
798
|
-
this.videoTransceiver.direction = 'sendrecv';
|
|
799
|
-
} else {
|
|
800
|
-
this.debug.log('🔄 Removing video track from stored transceiver');
|
|
801
|
-
await this.videoTransceiver.sender.replaceTrack(null);
|
|
802
|
-
this.videoTransceiver.direction = 'recvonly';
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
this.localStream = stream;
|
|
807
|
-
this.debug.log('✅ Stream set successfully using stored transceivers');
|
|
808
|
-
} else {
|
|
809
|
-
// Remove all tracks using stored references
|
|
810
|
-
if (this.audioTransceiver) {
|
|
811
|
-
this.debug.log('🔄 Removing audio track from stored transceiver');
|
|
812
|
-
await this.audioTransceiver.sender.replaceTrack(null);
|
|
813
|
-
this.audioTransceiver.direction = 'recvonly';
|
|
834
|
+
// Add audio tracks using addTrack()
|
|
835
|
+
audioTracks.forEach((audioTrack, index) => {
|
|
836
|
+
this.debug.log(`🎤 Adding audio track ${index} using addTrack()`);
|
|
837
|
+
try {
|
|
838
|
+
const audioSender = this.connection.addTrack(audioTrack, stream);
|
|
839
|
+
this.audioTransceiver = this.connection.getTransceivers().find(t => t.sender === audioSender);
|
|
840
|
+
|
|
841
|
+
// Setup audio sending monitoring
|
|
842
|
+
this.setupAudioSendingMonitoring(audioTrack);
|
|
843
|
+
this.debug.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} - track enabled: ${audioTrack.enabled}`);
|
|
844
|
+
} catch (error) {
|
|
845
|
+
this.debug.error(`❌ Failed to add audio track ${index}:`, error);
|
|
814
846
|
}
|
|
847
|
+
});
|
|
815
848
|
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
849
|
+
// Add video tracks using addTrack()
|
|
850
|
+
videoTracks.forEach((videoTrack, index) => {
|
|
851
|
+
this.debug.log(`🎥 Adding video track ${index} using addTrack()`);
|
|
852
|
+
try {
|
|
853
|
+
const videoSender = this.connection.addTrack(videoTrack, stream);
|
|
854
|
+
this.videoTransceiver = this.connection.getTransceivers().find(t => t.sender === videoSender);
|
|
855
|
+
this.debug.log(`🎥 SENDING VIDEO to peer ${this.peerId.substring(0, 8)} - track enabled: ${videoTrack.enabled}`);
|
|
856
|
+
} catch (error) {
|
|
857
|
+
this.debug.error(`❌ Failed to add video track ${index}:`, error);
|
|
820
858
|
}
|
|
859
|
+
});
|
|
821
860
|
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
// DEBUG: Log final transceivers after changes
|
|
829
|
-
const finalTransceivers = this.connection.getTransceivers();
|
|
830
|
-
this.debug.log('🔍 Final transceivers after stream change:', finalTransceivers.map(t => ({
|
|
861
|
+
this.localStream = stream;
|
|
862
|
+
this.debug.log('✅ Local stream added using addTrack() method');
|
|
863
|
+
|
|
864
|
+
// DEBUG: Log transceivers after adding tracks
|
|
865
|
+
const transceivers = this.connection.getTransceivers();
|
|
866
|
+
this.debug.log('🔍 Transceivers after addTrack():', transceivers.map(t => ({
|
|
831
867
|
kind: t.receiver?.track?.kind || 'unknown',
|
|
832
868
|
direction: t.direction,
|
|
833
869
|
hasTrack: !!t.sender?.track,
|
|
834
870
|
trackId: t.sender?.track?.id?.substring(0, 8) || 'none',
|
|
835
871
|
mid: t.mid
|
|
836
872
|
})));
|
|
873
|
+
}
|
|
837
874
|
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
875
|
+
/**
|
|
876
|
+
* Add or replace local media stream
|
|
877
|
+
*/
|
|
878
|
+
async setLocalStream(stream) {
|
|
879
|
+
if (!this.connection) {
|
|
880
|
+
throw new Error('Connection not initialized');
|
|
881
|
+
}
|
|
841
882
|
|
|
842
|
-
|
|
843
|
-
this.emit('renegotiationNeeded', { peerId: this.peerId });
|
|
883
|
+
this.debug.log(`Setting local stream for ${this.peerId}, current state: ${this.connection.connectionState}, signaling: ${this.connection.signalingState}`);
|
|
844
884
|
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
885
|
+
// First, remove any existing local tracks
|
|
886
|
+
const senders = this.connection.getSenders();
|
|
887
|
+
for (const sender of senders) {
|
|
888
|
+
if (sender.track) {
|
|
889
|
+
this.debug.log('�️ Removing existing track:', sender.track.kind);
|
|
890
|
+
this.connection.removeTrack(sender);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// Clear transceiver references
|
|
895
|
+
this.audioTransceiver = null;
|
|
896
|
+
this.videoTransceiver = null;
|
|
897
|
+
|
|
898
|
+
if (stream) {
|
|
899
|
+
this.debug.log('🎥 Adding new stream using addTrack() method');
|
|
900
|
+
await this.addLocalStreamWithAddTrack(stream);
|
|
854
901
|
} else {
|
|
855
|
-
|
|
856
|
-
this.debug.log('✅
|
|
857
|
-
this.emit('renegotiationNeeded', { peerId: this.peerId });
|
|
902
|
+
this.localStream = null;
|
|
903
|
+
this.debug.log('✅ All tracks removed');
|
|
858
904
|
}
|
|
859
905
|
|
|
906
|
+
this.debug.log('Updated local media stream for', this.peerId);
|
|
907
|
+
|
|
860
908
|
// CRITICAL: Force renegotiation when media changes
|
|
861
909
|
this.debug.log('✅ Stream updated - forcing renegotiation for media changes');
|
|
862
910
|
this.debug.log(` Current state: connectionState=${this.connection.connectionState}, signalingState=${this.connection.signalingState}`);
|
|
863
911
|
|
|
864
|
-
// Always trigger renegotiation when stream changes
|
|
912
|
+
// Always trigger renegotiation when stream changes
|
|
865
913
|
if (stream) {
|
|
866
914
|
setTimeout(() => {
|
|
867
915
|
this.debug.log('🔄 Forcing renegotiation for media stream changes');
|
|
868
916
|
this.emit('renegotiationNeeded', { peerId: this.peerId });
|
|
869
|
-
}, 200);
|
|
917
|
+
}, 200);
|
|
870
918
|
}
|
|
871
919
|
}
|
|
872
920
|
|
|
@@ -878,8 +926,19 @@ export class PeerConnection extends EventEmitter {
|
|
|
878
926
|
|
|
879
927
|
try {
|
|
880
928
|
// Create a new offer to break the stuck state
|
|
881
|
-
const offer = await
|
|
882
|
-
|
|
929
|
+
const offer = await Promise.race([
|
|
930
|
+
this.connection.createOffer({ iceRestart: true }),
|
|
931
|
+
new Promise((resolve, reject) =>
|
|
932
|
+
setTimeout(() => reject(new Error('forceConnectionRecovery createOffer timeout')), 10000)
|
|
933
|
+
)
|
|
934
|
+
]);
|
|
935
|
+
|
|
936
|
+
await Promise.race([
|
|
937
|
+
this.connection.setLocalDescription(offer),
|
|
938
|
+
new Promise((resolve, reject) =>
|
|
939
|
+
setTimeout(() => reject(new Error('forceConnectionRecovery setLocalDescription timeout')), 10000)
|
|
940
|
+
)
|
|
941
|
+
]);
|
|
883
942
|
|
|
884
943
|
// Emit recovery offer via mesh signaling
|
|
885
944
|
if (this.mesh && this.mesh.sendSignalingMessage) {
|
|
@@ -899,34 +958,6 @@ export class PeerConnection extends EventEmitter {
|
|
|
899
958
|
}
|
|
900
959
|
}
|
|
901
960
|
|
|
902
|
-
/**
|
|
903
|
-
* Helper method to set local stream tracks to existing transceivers
|
|
904
|
-
*/
|
|
905
|
-
async setLocalStreamToTransceivers(stream) {
|
|
906
|
-
if (stream) {
|
|
907
|
-
const audioTracks = stream.getAudioTracks();
|
|
908
|
-
const videoTracks = stream.getVideoTracks();
|
|
909
|
-
|
|
910
|
-
// Set audio track to stored audio transceiver
|
|
911
|
-
if (this.audioTransceiver && audioTracks.length > 0) {
|
|
912
|
-
this.debug.log('🔄 Setting audio track to stored audio transceiver');
|
|
913
|
-
await this.audioTransceiver.sender.replaceTrack(audioTracks[0]);
|
|
914
|
-
this.audioTransceiver.direction = 'sendrecv';
|
|
915
|
-
|
|
916
|
-
// Setup audio sending monitoring
|
|
917
|
-
this.setupAudioSendingMonitoring(audioTracks[0]);
|
|
918
|
-
this.debug.log(`🎤 SENDING AUDIO to peer ${this.peerId.substring(0, 8)} via transceiver - track enabled: ${audioTracks[0].enabled}`);
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
// Set video track to stored video transceiver
|
|
922
|
-
if (this.videoTransceiver && videoTracks.length > 0) {
|
|
923
|
-
this.debug.log('🔄 Setting video track to stored video transceiver');
|
|
924
|
-
await this.videoTransceiver.sender.replaceTrack(videoTracks[0]);
|
|
925
|
-
this.videoTransceiver.direction = 'sendrecv';
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
|
|
930
961
|
/**
|
|
931
962
|
* Setup audio data monitoring for received audio tracks
|
|
932
963
|
*/
|
|
@@ -1135,6 +1166,35 @@ export class PeerConnection extends EventEmitter {
|
|
|
1135
1166
|
return this.localStream;
|
|
1136
1167
|
}
|
|
1137
1168
|
|
|
1169
|
+
/**
|
|
1170
|
+
* Allow remote streams to be emitted (called after crypto verification)
|
|
1171
|
+
*/
|
|
1172
|
+
allowRemoteStreamEmission() {
|
|
1173
|
+
this.debug.log(`🔓 CRYPTO: Allowing remote stream emission for ${this.peerId.substring(0, 8)}...`);
|
|
1174
|
+
this.allowRemoteStreams = true;
|
|
1175
|
+
|
|
1176
|
+
// Emit any buffered remote streams
|
|
1177
|
+
while (this.pendingRemoteStreams.length > 0) {
|
|
1178
|
+
const streamEvent = this.pendingRemoteStreams.shift();
|
|
1179
|
+
this.debug.log(`🔓 CRYPTO: Emitting buffered remote stream from ${streamEvent.peerId.substring(0, 8)}...`);
|
|
1180
|
+
this.emit('remoteStream', streamEvent);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
/**
|
|
1185
|
+
* Block remote streams (called when crypto is required but not verified)
|
|
1186
|
+
*/
|
|
1187
|
+
blockRemoteStreamEmission() {
|
|
1188
|
+
// Check if crypto blocking is globally disabled (for video tests)
|
|
1189
|
+
if (typeof window !== 'undefined' && window.DISABLE_CRYPTO_BLOCKING) {
|
|
1190
|
+
this.debug.log(`🔓 CRYPTO: Video test mode - NOT blocking remote stream emission for ${this.peerId.substring(0, 8)}...`);
|
|
1191
|
+
return; // Don't block streams in video test mode
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
this.debug.log(`🔒 CRYPTO: Blocking remote stream emission for ${this.peerId.substring(0, 8)}...`);
|
|
1195
|
+
this.allowRemoteStreams = false;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1138
1198
|
/**
|
|
1139
1199
|
* Check if connection has video/audio capabilities
|
|
1140
1200
|
*/
|
|
@@ -1236,48 +1296,6 @@ export class PeerConnection extends EventEmitter {
|
|
|
1236
1296
|
return status;
|
|
1237
1297
|
}
|
|
1238
1298
|
|
|
1239
|
-
/**
|
|
1240
|
-
* Monitor data channel health when ICE connection is problematic but signaling is unavailable
|
|
1241
|
-
* This allows peer connections to survive signaling server outages
|
|
1242
|
-
*/
|
|
1243
|
-
monitorDataChannelHealth() {
|
|
1244
|
-
if (this.dataChannelHealthMonitor) {
|
|
1245
|
-
clearTimeout(this.dataChannelHealthMonitor);
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
this.debug.log(`📡 Monitoring data channel health for ${this.peerId} (signaling unavailable)`);
|
|
1249
|
-
|
|
1250
|
-
// Test data channel by sending a ping message
|
|
1251
|
-
const testDataChannel = () => {
|
|
1252
|
-
if (!this.dataChannel || this.dataChannel.readyState !== 'open' || this.isClosing) {
|
|
1253
|
-
this.debug.log(`❌ Data channel not available for ${this.peerId}, disconnecting`);
|
|
1254
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'data channel unavailable' });
|
|
1255
|
-
return;
|
|
1256
|
-
}
|
|
1257
|
-
|
|
1258
|
-
try {
|
|
1259
|
-
// Send a small ping message to test connectivity
|
|
1260
|
-
const pingMessage = {
|
|
1261
|
-
type: 'ping',
|
|
1262
|
-
timestamp: Date.now(),
|
|
1263
|
-
from: this.mesh?.peerId || 'unknown'
|
|
1264
|
-
};
|
|
1265
|
-
|
|
1266
|
-
this.dataChannel.send(JSON.stringify(pingMessage));
|
|
1267
|
-
this.debug.log(`✅ Data channel ping sent to ${this.peerId} - connection appears healthy`);
|
|
1268
|
-
|
|
1269
|
-
// Schedule next health check in 30 seconds
|
|
1270
|
-
this.dataChannelHealthMonitor = setTimeout(testDataChannel, 30000);
|
|
1271
|
-
} catch (error) {
|
|
1272
|
-
this.debug.error(`❌ Data channel ping failed for ${this.peerId}:`, error);
|
|
1273
|
-
this.emit('disconnected', { peerId: this.peerId, reason: 'data channel ping failed' });
|
|
1274
|
-
}
|
|
1275
|
-
};
|
|
1276
|
-
|
|
1277
|
-
// Start monitoring after a short delay
|
|
1278
|
-
this.dataChannelHealthMonitor = setTimeout(testDataChannel, 5000);
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
1299
|
/**
|
|
1282
1300
|
* Restart ICE using signaling coordination (WebSocket or mesh)
|
|
1283
1301
|
* This allows ICE restart to work even when the signaling server is down
|
|
@@ -1295,8 +1313,19 @@ export class PeerConnection extends EventEmitter {
|
|
|
1295
1313
|
this.connection.restartIce();
|
|
1296
1314
|
|
|
1297
1315
|
// Create a new offer with the restarted ICE
|
|
1298
|
-
const offer = await
|
|
1299
|
-
|
|
1316
|
+
const offer = await Promise.race([
|
|
1317
|
+
this.connection.createOffer({ iceRestart: true }),
|
|
1318
|
+
new Promise((resolve, reject) =>
|
|
1319
|
+
setTimeout(() => reject(new Error('ICE restart createOffer timeout')), 10000)
|
|
1320
|
+
)
|
|
1321
|
+
]);
|
|
1322
|
+
|
|
1323
|
+
await Promise.race([
|
|
1324
|
+
this.connection.setLocalDescription(offer),
|
|
1325
|
+
new Promise((resolve, reject) =>
|
|
1326
|
+
setTimeout(() => reject(new Error('ICE restart setLocalDescription timeout')), 10000)
|
|
1327
|
+
)
|
|
1328
|
+
]);
|
|
1300
1329
|
|
|
1301
1330
|
// Send the new offer via our mesh signaling system
|
|
1302
1331
|
if (this.mesh && this.mesh.sendSignalingMessage) {
|
|
@@ -1327,9 +1356,26 @@ export class PeerConnection extends EventEmitter {
|
|
|
1327
1356
|
this.debug.log(`🔄 Handling ICE restart offer from ${this.peerId}`);
|
|
1328
1357
|
|
|
1329
1358
|
try {
|
|
1330
|
-
await
|
|
1331
|
-
|
|
1332
|
-
|
|
1359
|
+
await Promise.race([
|
|
1360
|
+
this.connection.setRemoteDescription(offer),
|
|
1361
|
+
new Promise((resolve, reject) =>
|
|
1362
|
+
setTimeout(() => reject(new Error('ICE restart setRemoteDescription timeout')), 10000)
|
|
1363
|
+
)
|
|
1364
|
+
]);
|
|
1365
|
+
|
|
1366
|
+
const answer = await Promise.race([
|
|
1367
|
+
this.connection.createAnswer(),
|
|
1368
|
+
new Promise((resolve, reject) =>
|
|
1369
|
+
setTimeout(() => reject(new Error('ICE restart createAnswer timeout')), 10000)
|
|
1370
|
+
)
|
|
1371
|
+
]);
|
|
1372
|
+
|
|
1373
|
+
await Promise.race([
|
|
1374
|
+
this.connection.setLocalDescription(answer),
|
|
1375
|
+
new Promise((resolve, reject) =>
|
|
1376
|
+
setTimeout(() => reject(new Error('ICE restart setLocalDescription timeout')), 10000)
|
|
1377
|
+
)
|
|
1378
|
+
]);
|
|
1333
1379
|
|
|
1334
1380
|
// Send the answer back
|
|
1335
1381
|
if (this.mesh && this.mesh.sendSignalingMessage) {
|
|
@@ -1358,7 +1404,12 @@ export class PeerConnection extends EventEmitter {
|
|
|
1358
1404
|
this.debug.log(`🔄 Handling ICE restart answer from ${this.peerId}`);
|
|
1359
1405
|
|
|
1360
1406
|
try {
|
|
1361
|
-
await
|
|
1407
|
+
await Promise.race([
|
|
1408
|
+
this.connection.setRemoteDescription(answer),
|
|
1409
|
+
new Promise((resolve, reject) =>
|
|
1410
|
+
setTimeout(() => reject(new Error('ICE restart setRemoteDescription timeout')), 10000)
|
|
1411
|
+
)
|
|
1412
|
+
]);
|
|
1362
1413
|
this.debug.log(`✅ ICE restart completed for ${this.peerId}`);
|
|
1363
1414
|
} catch (error) {
|
|
1364
1415
|
this.debug.error(`Failed to handle ICE restart answer from ${this.peerId}:`, error);
|
|
@@ -1366,35 +1417,16 @@ export class PeerConnection extends EventEmitter {
|
|
|
1366
1417
|
}
|
|
1367
1418
|
}
|
|
1368
1419
|
|
|
1369
|
-
/**
|
|
1370
|
-
* Stop data channel health monitoring
|
|
1371
|
-
*/
|
|
1372
|
-
stopDataChannelHealthMonitoring() {
|
|
1373
|
-
if (this.dataChannelHealthMonitor) {
|
|
1374
|
-
clearTimeout(this.dataChannelHealthMonitor);
|
|
1375
|
-
this.dataChannelHealthMonitor = null;
|
|
1376
|
-
this.debug.log(`📡 Stopped data channel health monitoring for ${this.peerId}`);
|
|
1377
|
-
}
|
|
1378
|
-
}
|
|
1379
|
-
|
|
1380
1420
|
close() {
|
|
1381
1421
|
// Set flag to prevent disconnection events during intentional close
|
|
1382
1422
|
this.isClosing = true;
|
|
1383
1423
|
|
|
1384
|
-
// Clear any
|
|
1385
|
-
if (this.
|
|
1386
|
-
clearTimeout(this.
|
|
1387
|
-
this.
|
|
1388
|
-
}
|
|
1389
|
-
|
|
1390
|
-
if (this.connectingTimeout) {
|
|
1391
|
-
clearTimeout(this.connectingTimeout);
|
|
1392
|
-
this.connectingTimeout = null;
|
|
1424
|
+
// Clear any existing ICE timeout
|
|
1425
|
+
if (this.iceTimeoutId) {
|
|
1426
|
+
clearTimeout(this.iceTimeoutId);
|
|
1427
|
+
this.iceTimeoutId = null;
|
|
1393
1428
|
}
|
|
1394
1429
|
|
|
1395
|
-
// Stop data channel health monitoring
|
|
1396
|
-
this.stopDataChannelHealthMonitoring();
|
|
1397
|
-
|
|
1398
1430
|
if (this.connection) {
|
|
1399
1431
|
this.connection.close();
|
|
1400
1432
|
}
|