peerpigeon 0.0.1
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/LICENSE +21 -0
- package/README.md +1187 -0
- package/examples/browser/app-dht-disabled.js +42 -0
- package/examples/browser/app.js +51 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/index-dht-disabled.html +123 -0
- package/examples/browser/index.html +340 -0
- package/examples/browser/styles.css +1288 -0
- package/examples/browser/ui-clean.js +0 -0
- package/examples/browser/ui.js +1930 -0
- package/index.js +8 -0
- package/package.json +70 -0
- package/server/index.js +515 -0
- package/src/CleanupManager.js +181 -0
- package/src/ConnectionManager.js +841 -0
- package/src/EventEmitter.js +27 -0
- package/src/EvictionManager.js +257 -0
- package/src/GossipManager.js +416 -0
- package/src/MediaManager.js +225 -0
- package/src/MeshOptimizer.js +181 -0
- package/src/PeerConnection.js +831 -0
- package/src/PeerDiscovery.js +297 -0
- package/src/PeerPigeonMesh.js +703 -0
- package/src/SignalingClient.js +536 -0
- package/src/SignalingHandler.js +325 -0
- package/src/StorageManager.js +88 -0
- package/src/TimerUtils.js +46 -0
- package/src/WebDHT.js +1099 -0
- package/websocket-server/README.md +257 -0
- package/websocket-server/memory-leak-test.js +193 -0
- package/websocket-server/node_modules/.package-lock.json +29 -0
- package/websocket-server/node_modules/ws/LICENSE +20 -0
- package/websocket-server/node_modules/ws/README.md +548 -0
- package/websocket-server/node_modules/ws/browser.js +8 -0
- package/websocket-server/node_modules/ws/index.js +13 -0
- package/websocket-server/node_modules/ws/lib/buffer-util.js +131 -0
- package/websocket-server/node_modules/ws/lib/constants.js +18 -0
- package/websocket-server/node_modules/ws/lib/event-target.js +292 -0
- package/websocket-server/node_modules/ws/lib/extension.js +203 -0
- package/websocket-server/node_modules/ws/lib/limiter.js +55 -0
- package/websocket-server/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/websocket-server/node_modules/ws/lib/receiver.js +706 -0
- package/websocket-server/node_modules/ws/lib/sender.js +602 -0
- package/websocket-server/node_modules/ws/lib/stream.js +161 -0
- package/websocket-server/node_modules/ws/lib/subprotocol.js +62 -0
- package/websocket-server/node_modules/ws/lib/validation.js +152 -0
- package/websocket-server/node_modules/ws/lib/websocket-server.js +550 -0
- package/websocket-server/node_modules/ws/lib/websocket.js +1388 -0
- package/websocket-server/node_modules/ws/package.json +69 -0
- package/websocket-server/node_modules/ws/wrapper.mjs +8 -0
- package/websocket-server/package-lock.json +39 -0
- package/websocket-server/server.js +298 -0
- package/websocket-server/test.js +133 -0
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Manages gossip protocol for message propagation across the mesh network
|
|
5
|
+
* Ensures all peers receive messages even if not directly connected
|
|
6
|
+
*/
|
|
7
|
+
export class GossipManager extends EventEmitter {
|
|
8
|
+
constructor(mesh, connectionManager) {
|
|
9
|
+
super();
|
|
10
|
+
this.mesh = mesh;
|
|
11
|
+
this.connectionManager = connectionManager;
|
|
12
|
+
|
|
13
|
+
// Track message history to prevent infinite loops
|
|
14
|
+
this.seenMessages = new Map(); // messageId -> { timestamp, ttl }
|
|
15
|
+
this.messageHistory = new Map(); // messageId -> message content
|
|
16
|
+
|
|
17
|
+
// Configuration
|
|
18
|
+
this.maxTTL = 10; // Maximum hops before message expires
|
|
19
|
+
this.messageExpiryTime = 5 * 60 * 1000; // 5 minutes
|
|
20
|
+
this.cleanupInterval = 60 * 1000; // 1 minute
|
|
21
|
+
this.cleanupTimer = null; // Track cleanup timer for proper cleanup
|
|
22
|
+
|
|
23
|
+
this.startCleanupTimer();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Broadcast a message to all peers in the network using gossip protocol
|
|
28
|
+
*/
|
|
29
|
+
broadcastMessage(content, messageType = 'chat') {
|
|
30
|
+
// Validate content
|
|
31
|
+
if (content === undefined || content === null) {
|
|
32
|
+
console.error('Cannot broadcast message with undefined/null content');
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (messageType === 'chat' && (typeof content !== 'string' || content.trim().length === 0)) {
|
|
37
|
+
console.error('Cannot broadcast empty chat message');
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const messageId = this.generateMessageId();
|
|
42
|
+
const message = {
|
|
43
|
+
id: messageId,
|
|
44
|
+
type: 'gossip',
|
|
45
|
+
subtype: messageType,
|
|
46
|
+
content: content,
|
|
47
|
+
from: this.mesh.peerId,
|
|
48
|
+
timestamp: Date.now(),
|
|
49
|
+
ttl: this.maxTTL,
|
|
50
|
+
path: [this.mesh.peerId] // Track propagation path
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
console.log(`Broadcasting ${messageType} message: ${messageId.substring(0, 8)}... content: "${content}"`);
|
|
54
|
+
|
|
55
|
+
// Store our own message
|
|
56
|
+
this.seenMessages.set(messageId, {
|
|
57
|
+
timestamp: Date.now(),
|
|
58
|
+
ttl: this.maxTTL
|
|
59
|
+
});
|
|
60
|
+
this.messageHistory.set(messageId, message);
|
|
61
|
+
|
|
62
|
+
// Send to all connected peers
|
|
63
|
+
this.propagateMessage(message);
|
|
64
|
+
|
|
65
|
+
// Emit locally if it's a chat message
|
|
66
|
+
if (messageType === 'chat') {
|
|
67
|
+
this.emit('messageReceived', {
|
|
68
|
+
from: this.mesh.peerId,
|
|
69
|
+
content: content,
|
|
70
|
+
timestamp: message.timestamp,
|
|
71
|
+
messageId: messageId
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return messageId;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Send a direct message to a specific peer using gossip routing (DM)
|
|
80
|
+
* @param {string} targetPeerId - The destination peer's ID
|
|
81
|
+
* @param {string|object} content - The message content
|
|
82
|
+
* @returns {string|null} The message ID if sent, or null on error
|
|
83
|
+
*/
|
|
84
|
+
sendDirectMessage(targetPeerId, content) {
|
|
85
|
+
if (!targetPeerId || typeof targetPeerId !== 'string') {
|
|
86
|
+
console.error('Invalid targetPeerId for direct message');
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
const messageId = this.generateMessageId();
|
|
90
|
+
const message = {
|
|
91
|
+
id: messageId,
|
|
92
|
+
type: 'gossip',
|
|
93
|
+
subtype: 'dm',
|
|
94
|
+
content: content,
|
|
95
|
+
from: this.mesh.peerId,
|
|
96
|
+
to: targetPeerId,
|
|
97
|
+
timestamp: Date.now(),
|
|
98
|
+
ttl: this.maxTTL,
|
|
99
|
+
path: [this.mesh.peerId]
|
|
100
|
+
};
|
|
101
|
+
// Store our own message
|
|
102
|
+
this.seenMessages.set(messageId, {
|
|
103
|
+
timestamp: Date.now(),
|
|
104
|
+
ttl: this.maxTTL
|
|
105
|
+
});
|
|
106
|
+
this.messageHistory.set(messageId, message);
|
|
107
|
+
// Route to closest peer
|
|
108
|
+
this.propagateMessage(message);
|
|
109
|
+
return messageId;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Handle incoming gossip message from a peer
|
|
114
|
+
*/
|
|
115
|
+
handleGossipMessage(message, fromPeerId) {
|
|
116
|
+
console.log(`🔥🔥🔥 GOSSIP MESSAGE RECEIVED! From: ${fromPeerId?.substring(0, 8)}...`);
|
|
117
|
+
console.log(`🔥🔥🔥 Message:`, message);
|
|
118
|
+
|
|
119
|
+
const { id: messageId, ttl, from: originPeerId, subtype, content, timestamp, path, to } = message;
|
|
120
|
+
|
|
121
|
+
// Validate message structure
|
|
122
|
+
if (!messageId || !originPeerId || !subtype || content === undefined) {
|
|
123
|
+
console.error('Invalid gossip message structure:', message);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Check if we've already seen this message
|
|
128
|
+
if (this.seenMessages.has(messageId)) {
|
|
129
|
+
console.log(`Ignoring duplicate message: ${messageId.substring(0, 8)}...`);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Check TTL
|
|
134
|
+
if (ttl <= 0) {
|
|
135
|
+
console.log(`Message expired: ${messageId.substring(0, 8)}...`);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Check for loops (our peer ID in path)
|
|
140
|
+
if (path && path.includes(this.mesh.peerId)) {
|
|
141
|
+
console.log(`Preventing message loop: ${messageId.substring(0, 8)}...`);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
console.log(`Received gossip message: ${messageId.substring(0, 8)}... from ${fromPeerId.substring(0, 8)}... (TTL: ${ttl}, content: "${content}")`);
|
|
146
|
+
|
|
147
|
+
// Store message to prevent duplicates
|
|
148
|
+
this.seenMessages.set(messageId, {
|
|
149
|
+
timestamp: Date.now(),
|
|
150
|
+
ttl: ttl
|
|
151
|
+
});
|
|
152
|
+
this.messageHistory.set(messageId, message);
|
|
153
|
+
|
|
154
|
+
// Emit the message locally
|
|
155
|
+
if (subtype === 'chat') {
|
|
156
|
+
// Validate chat content
|
|
157
|
+
if (typeof content !== 'string' || content.trim().length === 0) {
|
|
158
|
+
console.warn(`Ignoring gossip chat message with invalid content:`, content);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
this.emit('messageReceived', {
|
|
163
|
+
from: originPeerId,
|
|
164
|
+
content: content,
|
|
165
|
+
timestamp: timestamp,
|
|
166
|
+
messageId: messageId,
|
|
167
|
+
hops: this.maxTTL - ttl,
|
|
168
|
+
direct: false // Flag to indicate this was a gossip message
|
|
169
|
+
});
|
|
170
|
+
} else if (subtype === 'peer-announcement') {
|
|
171
|
+
this.handlePeerAnnouncement(content, originPeerId);
|
|
172
|
+
} else if (subtype === 'dm') {
|
|
173
|
+
// Direct message logic
|
|
174
|
+
if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
|
|
175
|
+
// This peer is the target, emit to UI
|
|
176
|
+
this.emit('messageReceived', {
|
|
177
|
+
from: originPeerId,
|
|
178
|
+
content: content,
|
|
179
|
+
timestamp: timestamp,
|
|
180
|
+
messageId: messageId,
|
|
181
|
+
hops: this.maxTTL - ttl,
|
|
182
|
+
direct: true // Flag to indicate this was a direct message
|
|
183
|
+
});
|
|
184
|
+
// Do NOT relay further if we are the recipient
|
|
185
|
+
return;
|
|
186
|
+
} else {
|
|
187
|
+
// Not the target, relay silently (do not emit)
|
|
188
|
+
}
|
|
189
|
+
} else if (subtype === 'dht-routing') {
|
|
190
|
+
// DHT routing message - check if we're the target
|
|
191
|
+
if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
|
|
192
|
+
console.log(`DHT: Received routed message for us from ${originPeerId.substring(0, 8)}`);
|
|
193
|
+
// We are the target, deliver the DHT message locally
|
|
194
|
+
if (this.mesh.webDHT && content) {
|
|
195
|
+
// Simulate receiving the message from the original sender
|
|
196
|
+
this.mesh.webDHT.handleMessage(content, originPeerId);
|
|
197
|
+
}
|
|
198
|
+
// Do NOT relay further since we are the recipient
|
|
199
|
+
return;
|
|
200
|
+
} else {
|
|
201
|
+
console.log(`DHT: Routing message for ${to?.substring(0, 8)} (not us)`);
|
|
202
|
+
// Not the target, continue routing
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// Propagate to other peers with decremented TTL
|
|
206
|
+
const updatedMessage = {
|
|
207
|
+
...message,
|
|
208
|
+
ttl: ttl - 1,
|
|
209
|
+
path: [...(path || []), this.mesh.peerId]
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
this.propagateMessage(updatedMessage, fromPeerId);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Handle peer announcements received via gossip
|
|
217
|
+
*/
|
|
218
|
+
handlePeerAnnouncement(announcementData, originPeerId) {
|
|
219
|
+
const { peerId: announcedPeerId } = announcementData;
|
|
220
|
+
|
|
221
|
+
console.log(`Gossip peer announcement: ${announcedPeerId.substring(0, 8)}... via ${originPeerId.substring(0, 8)}...`);
|
|
222
|
+
|
|
223
|
+
// Add to discovered peers if we don't know about them
|
|
224
|
+
if (!this.mesh.peerDiscovery.hasPeer(announcedPeerId) &&
|
|
225
|
+
announcedPeerId !== this.mesh.peerId) {
|
|
226
|
+
|
|
227
|
+
this.mesh.emit('statusChanged', {
|
|
228
|
+
type: 'info',
|
|
229
|
+
message: `Discovered peer ${announcedPeerId.substring(0, 8)}... via gossip`
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
this.mesh.peerDiscovery.addDiscoveredPeer(announcedPeerId);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Broadcast peer announcement via gossip when we connect
|
|
238
|
+
*/
|
|
239
|
+
announcePeer(peerId = this.mesh.peerId) {
|
|
240
|
+
const announcementData = {
|
|
241
|
+
peerId: peerId,
|
|
242
|
+
timestamp: Date.now()
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
console.log(`Gossiping peer announcement for: ${peerId.substring(0, 8)}...`);
|
|
246
|
+
this.broadcastMessage(announcementData, 'peer-announcement');
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Propagate message to ALL peers that can receive messages - ignore connection states!
|
|
251
|
+
*/
|
|
252
|
+
propagateMessage(message, excludePeerId = null) {
|
|
253
|
+
// DM and DHT routing: route to closest peer(s) for messages with specific targets
|
|
254
|
+
if ((message.subtype === 'dm' || message.subtype === 'dht-routing') && message.to) {
|
|
255
|
+
const targetId = message.to;
|
|
256
|
+
const allPeers = Array.from(this.connectionManager.peers.values());
|
|
257
|
+
const capablePeers = allPeers.filter(peerConnection => {
|
|
258
|
+
return peerConnection.dataChannel && peerConnection.dataChannel.readyState === 'open';
|
|
259
|
+
});
|
|
260
|
+
// Improved XOR distance for 40-char hex peer IDs
|
|
261
|
+
function xorDistance(a, b) {
|
|
262
|
+
if (!a || !b) return Number.MAX_SAFE_INTEGER;
|
|
263
|
+
let dist = 0n;
|
|
264
|
+
for (let i = 0; i < 40; i += 8) {
|
|
265
|
+
const aChunk = a.substring(i, i + 8);
|
|
266
|
+
const bChunk = b.substring(i, i + 8);
|
|
267
|
+
dist = (dist << 32n) + (BigInt('0x' + aChunk) ^ BigInt('0x' + bChunk));
|
|
268
|
+
}
|
|
269
|
+
return dist;
|
|
270
|
+
}
|
|
271
|
+
let minDist = null;
|
|
272
|
+
let closestPeers = [];
|
|
273
|
+
capablePeers.forEach(peerConnection => {
|
|
274
|
+
if (peerConnection.peerId === excludePeerId || message.ttl <= 0) return;
|
|
275
|
+
const dist = xorDistance(peerConnection.peerId, targetId);
|
|
276
|
+
if (minDist === null || dist < minDist) {
|
|
277
|
+
minDist = dist;
|
|
278
|
+
closestPeers = [peerConnection];
|
|
279
|
+
} else if (dist === minDist) {
|
|
280
|
+
closestPeers.push(peerConnection);
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
if (closestPeers.length > 0) {
|
|
284
|
+
closestPeers.forEach(peer => {
|
|
285
|
+
try {
|
|
286
|
+
peer.sendMessage(message);
|
|
287
|
+
const routingType = message.subtype === 'dht-routing' ? 'DHT' : 'DM';
|
|
288
|
+
console.log(`${routingType} routed to closest peer: ${peer.peerId.substring(0, 8)}...`);
|
|
289
|
+
} catch (error) {
|
|
290
|
+
console.error(`${message.subtype} routing failed:`, error);
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
} else {
|
|
294
|
+
// Fallback: relay to all capable peers except sender
|
|
295
|
+
capablePeers.forEach(peerConnection => {
|
|
296
|
+
if (peerConnection.peerId === excludePeerId || message.ttl <= 0) return;
|
|
297
|
+
try {
|
|
298
|
+
peerConnection.sendMessage(message);
|
|
299
|
+
const routingType = message.subtype === 'dht-routing' ? 'DHT' : 'DM';
|
|
300
|
+
console.log(`${routingType} fallback relay to: ${peerConnection.peerId.substring(0, 8)}...`);
|
|
301
|
+
} catch (error) {
|
|
302
|
+
console.error(`${message.subtype} fallback relay failed:`, error);
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
// AGGRESSIVE: Get ALL peers regardless of status - we only care if we can send a message
|
|
309
|
+
const allPeers = Array.from(this.connectionManager.peers.values());
|
|
310
|
+
const capablePeers = allPeers.filter(peerConnection => {
|
|
311
|
+
// ONLY requirement: does the peer have an open data channel?
|
|
312
|
+
return peerConnection.dataChannel &&
|
|
313
|
+
peerConnection.dataChannel.readyState === 'open';
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
let propagatedTo = 0;
|
|
317
|
+
|
|
318
|
+
console.log(`🚀 AGGRESSIVE GOSSIP: Found ${capablePeers.length}/${allPeers.length} peers with open data channels`);
|
|
319
|
+
console.log(`Message: ${message.id.substring(0, 8)}..., TTL: ${message.ttl}, Exclude: ${excludePeerId?.substring(0, 8) || 'none'}`);
|
|
320
|
+
|
|
321
|
+
// Debug: show state of ALL peers
|
|
322
|
+
allPeers.forEach(peerConnection => {
|
|
323
|
+
const status = peerConnection.getStatus();
|
|
324
|
+
const dataChannelState = peerConnection.dataChannel?.readyState || 'none';
|
|
325
|
+
const canSend = peerConnection.dataChannel && peerConnection.dataChannel.readyState === 'open';
|
|
326
|
+
const isExcluded = peerConnection.peerId === excludePeerId;
|
|
327
|
+
console.log(` ${peerConnection.peerId.substring(0, 8)}... - Status: ${status}, DataChannel: ${dataChannelState}, CanSend: ${canSend}, Excluded: ${isExcluded}`);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
capablePeers.forEach(peerConnection => {
|
|
331
|
+
const peerId = peerConnection.peerId;
|
|
332
|
+
|
|
333
|
+
// Don't send back to sender or if TTL expired
|
|
334
|
+
if (peerId === excludePeerId || message.ttl <= 0) {
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
try {
|
|
339
|
+
peerConnection.sendMessage(message);
|
|
340
|
+
propagatedTo++;
|
|
341
|
+
console.log(`✅ GOSSIP SUCCESS: Sent to ${peerId.substring(0, 8)}...`);
|
|
342
|
+
} catch (error) {
|
|
343
|
+
console.error(`❌ GOSSIP FAILED: Could not send to ${peerId.substring(0, 8)}...`, error);
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
console.log(`🎯 GOSSIP RESULT: Propagated to ${propagatedTo}/${capablePeers.length} capable peers`);
|
|
348
|
+
|
|
349
|
+
if (propagatedTo === 0 && allPeers.length > 0) {
|
|
350
|
+
console.error(`🚨 GOSSIP FAILURE: NO PROPAGATION! ${allPeers.length} total peers, ${capablePeers.length} with data channels`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Get message statistics
|
|
356
|
+
*/
|
|
357
|
+
getStats() {
|
|
358
|
+
return {
|
|
359
|
+
seenMessages: this.seenMessages.size,
|
|
360
|
+
storedMessages: this.messageHistory.size,
|
|
361
|
+
maxTTL: this.maxTTL,
|
|
362
|
+
messageExpiryTime: this.messageExpiryTime
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Generate unique message ID
|
|
368
|
+
*/
|
|
369
|
+
generateMessageId() {
|
|
370
|
+
const array = new Uint8Array(16);
|
|
371
|
+
crypto.getRandomValues(array);
|
|
372
|
+
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Clean up expired messages
|
|
377
|
+
*/
|
|
378
|
+
startCleanupTimer() {
|
|
379
|
+
if (this.cleanupTimer) {
|
|
380
|
+
clearInterval(this.cleanupTimer);
|
|
381
|
+
}
|
|
382
|
+
this.cleanupTimer = window.setInterval.call(window, () => {
|
|
383
|
+
this.cleanupExpiredMessages();
|
|
384
|
+
}, this.cleanupInterval);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
cleanupExpiredMessages() {
|
|
388
|
+
const now = Date.now();
|
|
389
|
+
let cleaned = 0;
|
|
390
|
+
|
|
391
|
+
// Clean up seen messages
|
|
392
|
+
this.seenMessages.forEach((data, messageId) => {
|
|
393
|
+
if (now - data.timestamp > this.messageExpiryTime) {
|
|
394
|
+
this.seenMessages.delete(messageId);
|
|
395
|
+
this.messageHistory.delete(messageId);
|
|
396
|
+
cleaned++;
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
if (cleaned > 0) {
|
|
401
|
+
console.log(`Cleaned up ${cleaned} expired gossip messages`);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Cleanup method
|
|
407
|
+
*/
|
|
408
|
+
cleanup() {
|
|
409
|
+
if (this.cleanupTimer) {
|
|
410
|
+
clearInterval(this.cleanupTimer);
|
|
411
|
+
this.cleanupTimer = null;
|
|
412
|
+
}
|
|
413
|
+
this.seenMessages.clear();
|
|
414
|
+
this.messageHistory.clear();
|
|
415
|
+
}
|
|
416
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
|
|
3
|
+
export class MediaManager extends EventEmitter {
|
|
4
|
+
constructor() {
|
|
5
|
+
super();
|
|
6
|
+
this.localStream = null;
|
|
7
|
+
this.isVideoEnabled = false;
|
|
8
|
+
this.isAudioEnabled = false;
|
|
9
|
+
this.devices = {
|
|
10
|
+
cameras: [],
|
|
11
|
+
microphones: [],
|
|
12
|
+
speakers: []
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
this.constraints = {
|
|
16
|
+
video: {
|
|
17
|
+
width: { ideal: 640 },
|
|
18
|
+
height: { ideal: 480 },
|
|
19
|
+
frameRate: { ideal: 30 }
|
|
20
|
+
},
|
|
21
|
+
audio: {
|
|
22
|
+
echoCancellation: true,
|
|
23
|
+
noiseSuppression: true,
|
|
24
|
+
autoGainControl: true
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Initialize media devices and permissions
|
|
31
|
+
*/
|
|
32
|
+
async init() {
|
|
33
|
+
try {
|
|
34
|
+
// Enumerate available devices
|
|
35
|
+
await this.enumerateDevices();
|
|
36
|
+
return true;
|
|
37
|
+
} catch (error) {
|
|
38
|
+
console.error('Failed to initialize media manager:', error);
|
|
39
|
+
this.emit('error', { type: 'init', error });
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Get available media devices
|
|
46
|
+
*/
|
|
47
|
+
async enumerateDevices() {
|
|
48
|
+
try {
|
|
49
|
+
const devices = await navigator.mediaDevices.enumerateDevices();
|
|
50
|
+
|
|
51
|
+
this.devices.cameras = devices.filter(device => device.kind === 'videoinput');
|
|
52
|
+
this.devices.microphones = devices.filter(device => device.kind === 'audioinput');
|
|
53
|
+
this.devices.speakers = devices.filter(device => device.kind === 'audiooutput');
|
|
54
|
+
|
|
55
|
+
this.emit('devicesUpdated', this.devices);
|
|
56
|
+
return this.devices;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
console.error('Failed to enumerate devices:', error);
|
|
59
|
+
this.emit('error', { type: 'enumerate', error });
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Start local media stream with specified constraints
|
|
66
|
+
*/
|
|
67
|
+
async startLocalStream(options = {}) {
|
|
68
|
+
const { video = false, audio = false, deviceIds = {} } = options;
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
// Stop existing stream first
|
|
72
|
+
if (this.localStream) {
|
|
73
|
+
this.stopLocalStream();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const constraints = {};
|
|
77
|
+
|
|
78
|
+
if (video) {
|
|
79
|
+
constraints.video = { ...this.constraints.video };
|
|
80
|
+
if (deviceIds.camera) {
|
|
81
|
+
constraints.video.deviceId = { exact: deviceIds.camera };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (audio) {
|
|
86
|
+
constraints.audio = { ...this.constraints.audio };
|
|
87
|
+
if (deviceIds.microphone) {
|
|
88
|
+
constraints.audio.deviceId = { exact: deviceIds.microphone };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (!video && !audio) {
|
|
93
|
+
throw new Error('At least one of video or audio must be enabled');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
this.localStream = await navigator.mediaDevices.getUserMedia(constraints);
|
|
97
|
+
this.isVideoEnabled = video;
|
|
98
|
+
this.isAudioEnabled = audio;
|
|
99
|
+
|
|
100
|
+
console.log('Local media stream started:', {
|
|
101
|
+
video: this.isVideoEnabled,
|
|
102
|
+
audio: this.isAudioEnabled,
|
|
103
|
+
tracks: this.localStream.getTracks().map(track => ({
|
|
104
|
+
kind: track.kind,
|
|
105
|
+
enabled: track.enabled,
|
|
106
|
+
label: track.label
|
|
107
|
+
}))
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
this.emit('localStreamStarted', {
|
|
111
|
+
stream: this.localStream,
|
|
112
|
+
video: this.isVideoEnabled,
|
|
113
|
+
audio: this.isAudioEnabled
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
return this.localStream;
|
|
117
|
+
} catch (error) {
|
|
118
|
+
console.error('Failed to start local media stream:', error);
|
|
119
|
+
this.emit('error', { type: 'getUserMedia', error });
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Stop local media stream
|
|
126
|
+
*/
|
|
127
|
+
stopLocalStream() {
|
|
128
|
+
if (this.localStream) {
|
|
129
|
+
console.log('Stopping local media stream');
|
|
130
|
+
this.localStream.getTracks().forEach(track => {
|
|
131
|
+
track.stop();
|
|
132
|
+
});
|
|
133
|
+
this.localStream = null;
|
|
134
|
+
this.isVideoEnabled = false;
|
|
135
|
+
this.isAudioEnabled = false;
|
|
136
|
+
|
|
137
|
+
this.emit('localStreamStopped');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Toggle video track on/off
|
|
143
|
+
*/
|
|
144
|
+
toggleVideo() {
|
|
145
|
+
if (this.localStream) {
|
|
146
|
+
const videoTrack = this.localStream.getVideoTracks()[0];
|
|
147
|
+
if (videoTrack) {
|
|
148
|
+
videoTrack.enabled = !videoTrack.enabled;
|
|
149
|
+
this.emit('videoToggled', { enabled: videoTrack.enabled });
|
|
150
|
+
return videoTrack.enabled;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Toggle audio track on/off
|
|
158
|
+
*/
|
|
159
|
+
toggleAudio() {
|
|
160
|
+
if (this.localStream) {
|
|
161
|
+
const audioTrack = this.localStream.getAudioTracks()[0];
|
|
162
|
+
if (audioTrack) {
|
|
163
|
+
audioTrack.enabled = !audioTrack.enabled;
|
|
164
|
+
this.emit('audioToggled', { enabled: audioTrack.enabled });
|
|
165
|
+
return audioTrack.enabled;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Get current media state
|
|
173
|
+
*/
|
|
174
|
+
getMediaState() {
|
|
175
|
+
const state = {
|
|
176
|
+
hasLocalStream: !!this.localStream,
|
|
177
|
+
videoEnabled: false,
|
|
178
|
+
audioEnabled: false,
|
|
179
|
+
devices: this.devices
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
if (this.localStream) {
|
|
183
|
+
const videoTrack = this.localStream.getVideoTracks()[0];
|
|
184
|
+
const audioTrack = this.localStream.getAudioTracks()[0];
|
|
185
|
+
|
|
186
|
+
state.videoEnabled = videoTrack ? videoTrack.enabled : false;
|
|
187
|
+
state.audioEnabled = audioTrack ? audioTrack.enabled : false;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return state;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Check if browser supports required APIs
|
|
195
|
+
*/
|
|
196
|
+
static checkSupport() {
|
|
197
|
+
const support = {
|
|
198
|
+
getUserMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
|
|
199
|
+
enumerateDevices: !!(navigator.mediaDevices && navigator.mediaDevices.enumerateDevices),
|
|
200
|
+
webRTC: !!(window.RTCPeerConnection)
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
support.fullSupport = support.getUserMedia && support.enumerateDevices && support.webRTC;
|
|
204
|
+
return support;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Get media permissions status
|
|
209
|
+
*/
|
|
210
|
+
async getPermissions() {
|
|
211
|
+
try {
|
|
212
|
+
const permissions = {};
|
|
213
|
+
|
|
214
|
+
if (navigator.permissions) {
|
|
215
|
+
permissions.camera = await navigator.permissions.query({ name: 'camera' });
|
|
216
|
+
permissions.microphone = await navigator.permissions.query({ name: 'microphone' });
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return permissions;
|
|
220
|
+
} catch (error) {
|
|
221
|
+
console.warn('Could not check media permissions:', error);
|
|
222
|
+
return {};
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|