@yrzhao/aves-core 0.1.0 → 0.2.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.
- package/README.md +109 -344
- package/dist/core/AvesClient.d.ts +15 -61
- package/dist/core/AvesClient.js +140 -137
- package/dist/core/SignalingClient.d.ts +10 -3
- package/dist/core/SignalingClient.js +122 -28
- package/dist/core/WebRTCManager.d.ts +108 -39
- package/dist/core/WebRTCManager.js +672 -182
- package/dist/esm/core/AvesClient.d.ts +15 -61
- package/dist/esm/core/AvesClient.js +140 -137
- package/dist/esm/core/SignalingClient.d.ts +10 -3
- package/dist/esm/core/SignalingClient.js +122 -28
- package/dist/esm/core/WebRTCManager.d.ts +108 -39
- package/dist/esm/core/WebRTCManager.js +672 -182
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/types/types.d.ts +63 -4
- package/dist/index.d.ts +1 -1
- package/dist/types/types.d.ts +63 -4
- package/package.json +1 -1
|
@@ -1,150 +1,239 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.WebRTCManager = void 0;
|
|
4
|
+
const DEFAULT_FILE_CHUNK_SIZE = 16 * 1024;
|
|
5
|
+
const FILE_CHANNEL_LABEL = "file";
|
|
6
|
+
const MESSAGE_CHANNEL_LABEL = "data";
|
|
7
|
+
const FILE_PROTOCOL = "aves:file-control";
|
|
8
|
+
const FILE_READY_TIMEOUT_MS = 10000;
|
|
9
|
+
const FILE_COMPLETE_TIMEOUT_MS = 10000;
|
|
10
|
+
const FILE_END_MARKER_PREFIX = "__aves_file_end__:";
|
|
4
11
|
/**
|
|
5
|
-
* WebRTCManager - Manages WebRTC PeerConnections and
|
|
6
|
-
*
|
|
7
|
-
* This class handles the low-level WebRTC connection management including:
|
|
8
|
-
* - Creating and managing RTCPeerConnection instances
|
|
9
|
-
* - Creating and managing RTCDataChannel instances
|
|
10
|
-
* - Handling ICE candidate exchange
|
|
11
|
-
* - Serializing and deserializing messages
|
|
12
|
-
* - Managing connection lifecycle and cleanup
|
|
12
|
+
* WebRTCManager - Manages WebRTC PeerConnections, DataChannels, and media tracks
|
|
13
13
|
*/
|
|
14
14
|
class WebRTCManager {
|
|
15
|
-
constructor(iceServers) {
|
|
15
|
+
constructor(iceServers, fileChunkSize = DEFAULT_FILE_CHUNK_SIZE) {
|
|
16
16
|
this.peerConnections = new Map();
|
|
17
17
|
this.dataChannels = new Map();
|
|
18
18
|
this.iceServers = iceServers;
|
|
19
|
+
this.fileChunkSize = this.validateChunkSize(fileChunkSize);
|
|
19
20
|
this.messageCallbacks = new Set();
|
|
20
21
|
this.connectionStateCallbacks = new Map();
|
|
21
22
|
this.dataChannelStateCallbacks = new Map();
|
|
22
23
|
this.iceCandidateCallbacks = new Map();
|
|
24
|
+
this.fileTransferStartedCallbacks = new Set();
|
|
25
|
+
this.fileTransferProgressCallbacks = new Set();
|
|
26
|
+
this.fileTransferCompletedCallbacks = new Set();
|
|
27
|
+
this.fileTransferFailedCallbacks = new Set();
|
|
28
|
+
this.remoteAudioTrackCallbacks = new Set();
|
|
29
|
+
this.localAudioStateCallbacks = new Set();
|
|
30
|
+
this.outgoingTransfers = new Map();
|
|
31
|
+
this.incomingTransfers = new Map();
|
|
32
|
+
this.readyResolvers = new Map();
|
|
33
|
+
this.completionResolvers = new Map();
|
|
34
|
+
this.audioSenders = new Map();
|
|
35
|
+
this.remoteAudioStreams = new Map();
|
|
36
|
+
this.localAudioStream = null;
|
|
37
|
+
this.localAudioTrack = null;
|
|
38
|
+
this.isMuted = false;
|
|
23
39
|
}
|
|
24
40
|
/**
|
|
25
|
-
* Create a new PeerConnection for the specified peer
|
|
26
|
-
* If a connection already exists, returns the existing connection
|
|
41
|
+
* Create a new PeerConnection for the specified peer.
|
|
42
|
+
* If a connection already exists, returns the existing connection.
|
|
27
43
|
*/
|
|
28
44
|
createPeerConnection(peerId) {
|
|
29
45
|
if (this.peerConnections.has(peerId)) {
|
|
30
|
-
console.log(`[WebRTCManager] Reusing existing PeerConnection for ${peerId}`);
|
|
31
46
|
return this.peerConnections.get(peerId);
|
|
32
47
|
}
|
|
33
|
-
console.log(`[WebRTCManager] Creating new PeerConnection for ${peerId}`);
|
|
34
48
|
const pc = new RTCPeerConnection({
|
|
35
49
|
iceServers: this.iceServers,
|
|
36
50
|
});
|
|
37
51
|
this.peerConnections.set(peerId, pc);
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
console.log(`[WebRTCManager] Connection state for ${peerId}: ${pc.connectionState}`);
|
|
41
|
-
const callbacks = this.connectionStateCallbacks.get(peerId);
|
|
42
|
-
if (callbacks) {
|
|
43
|
-
callbacks.forEach((callback) => callback(pc.connectionState));
|
|
44
|
-
}
|
|
45
|
-
// Auto-cleanup on failed/closed/disconnected states
|
|
46
|
-
if (pc.connectionState === "failed" ||
|
|
47
|
-
pc.connectionState === "closed" ||
|
|
48
|
-
pc.connectionState === "disconnected") {
|
|
49
|
-
this.closePeerConnection(peerId);
|
|
50
|
-
}
|
|
51
|
-
};
|
|
52
|
+
this.dataChannels.set(peerId, {});
|
|
53
|
+
this.setupPeerConnection(peerId, pc);
|
|
52
54
|
return pc;
|
|
53
55
|
}
|
|
54
56
|
/**
|
|
55
|
-
* Create an offer for the specified peer
|
|
56
|
-
*
|
|
57
|
+
* Create an offer for the specified peer.
|
|
58
|
+
* The offer side creates both the message and file channels.
|
|
57
59
|
*/
|
|
58
60
|
async createOffer(peerId) {
|
|
59
|
-
const pc = this.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
}
|
|
63
|
-
console.log(`[WebRTCManager] Creating offer for ${peerId}, current state: ${pc.signalingState}`);
|
|
64
|
-
// Create DataChannel (offer side creates it)
|
|
65
|
-
const dataChannel = pc.createDataChannel("data");
|
|
66
|
-
this.setupDataChannel(peerId, dataChannel);
|
|
61
|
+
const pc = this.getPeerConnection(peerId);
|
|
62
|
+
this.ensureDataChannel(peerId, pc, MESSAGE_CHANNEL_LABEL);
|
|
63
|
+
this.ensureDataChannel(peerId, pc, FILE_CHANNEL_LABEL);
|
|
67
64
|
const offer = await pc.createOffer();
|
|
68
65
|
await pc.setLocalDescription(offer);
|
|
69
|
-
console.log(`[WebRTCManager] Created offer for ${peerId}, new state: ${pc.signalingState}`);
|
|
70
66
|
return offer;
|
|
71
67
|
}
|
|
72
68
|
/**
|
|
73
|
-
* Create an answer for the specified peer
|
|
74
|
-
*
|
|
69
|
+
* Create an answer for the specified peer.
|
|
70
|
+
* The answer side receives data channels from the remote offer.
|
|
75
71
|
*/
|
|
76
72
|
async createAnswer(peerId, offer) {
|
|
77
|
-
const pc = this.
|
|
78
|
-
if (!pc) {
|
|
79
|
-
throw new Error(`No peer connection found for ${peerId}`);
|
|
80
|
-
}
|
|
81
|
-
// Listen for DataChannel (answer side receives it)
|
|
73
|
+
const pc = this.getPeerConnection(peerId);
|
|
82
74
|
pc.ondatachannel = (event) => {
|
|
83
75
|
this.setupDataChannel(peerId, event.channel);
|
|
84
76
|
};
|
|
85
|
-
console.log(`[WebRTCManager] Creating answer for ${peerId}, current state: ${pc.signalingState}`);
|
|
86
77
|
await pc.setRemoteDescription(new RTCSessionDescription(offer));
|
|
87
|
-
console.log(`[WebRTCManager] Set remote offer for ${peerId}, new state: ${pc.signalingState}`);
|
|
88
78
|
const answer = await pc.createAnswer();
|
|
89
79
|
await pc.setLocalDescription(answer);
|
|
90
|
-
console.log(`[WebRTCManager] Created answer for ${peerId}, new state: ${pc.signalingState}`);
|
|
91
80
|
return answer;
|
|
92
81
|
}
|
|
93
82
|
/**
|
|
94
|
-
* Set the remote answer for the specified peer
|
|
83
|
+
* Set the remote answer for the specified peer.
|
|
95
84
|
*/
|
|
96
85
|
async setRemoteAnswer(peerId, answer) {
|
|
97
|
-
const pc = this.
|
|
98
|
-
if (!pc) {
|
|
99
|
-
throw new Error(`No peer connection found for ${peerId}`);
|
|
100
|
-
}
|
|
101
|
-
console.log(`[WebRTCManager] Setting remote answer for ${peerId}, current state: ${pc.signalingState}`);
|
|
102
|
-
// Check if we're in the correct state to set remote answer
|
|
103
|
-
if (pc.signalingState !== "have-local-offer") {
|
|
104
|
-
throw new Error(`Cannot set remote answer for ${peerId}: wrong state ${pc.signalingState}, expected have-local-offer`);
|
|
105
|
-
}
|
|
86
|
+
const pc = this.getPeerConnection(peerId);
|
|
106
87
|
await pc.setRemoteDescription(new RTCSessionDescription(answer));
|
|
107
|
-
console.log(`[WebRTCManager] Successfully set remote answer for ${peerId}`);
|
|
108
88
|
}
|
|
109
89
|
/**
|
|
110
|
-
* Add an ICE candidate for the specified peer
|
|
90
|
+
* Add an ICE candidate for the specified peer.
|
|
111
91
|
*/
|
|
112
92
|
async addIceCandidate(peerId, candidate) {
|
|
113
|
-
const pc = this.
|
|
114
|
-
|
|
115
|
-
|
|
93
|
+
const pc = this.getPeerConnection(peerId);
|
|
94
|
+
await pc.addIceCandidate(new RTCIceCandidate(candidate));
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Send a JSON message to all connected peers.
|
|
98
|
+
*/
|
|
99
|
+
sendMessage(message) {
|
|
100
|
+
const errors = [];
|
|
101
|
+
this.dataChannels.forEach((storedChannels, peerId) => {
|
|
102
|
+
const channels = this.normalizePeerChannels(storedChannels);
|
|
103
|
+
if (!channels.message || channels.message.readyState !== "open") {
|
|
104
|
+
errors.push(peerId);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
channels.message.send(JSON.stringify(message));
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
errors.push(peerId);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
if (errors.length > 0) {
|
|
115
|
+
throw new Error(`DataChannel not ready for peers: ${errors.join(", ")}`);
|
|
116
116
|
}
|
|
117
|
-
|
|
118
|
-
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Send a JSON message to a specific peer.
|
|
120
|
+
*/
|
|
121
|
+
sendMessageToPeer(peerId, message) {
|
|
122
|
+
const dataChannel = this.getMessageChannel(peerId);
|
|
123
|
+
if (dataChannel.readyState !== "open") {
|
|
124
|
+
throw new Error(`DataChannel not ready for ${peerId}, state: ${dataChannel.readyState}`);
|
|
119
125
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
126
|
+
dataChannel.send(JSON.stringify(message));
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Send a file to one peer or broadcast to every connected peer.
|
|
130
|
+
*/
|
|
131
|
+
async sendFile(blob, options = {}) {
|
|
132
|
+
const peerIds = options.peerId
|
|
133
|
+
? [options.peerId]
|
|
134
|
+
: this.getActivePeers().filter((peerId) => this.isFileChannelReady(peerId));
|
|
135
|
+
if (peerIds.length === 0) {
|
|
136
|
+
throw new Error("No file channel is ready");
|
|
137
|
+
}
|
|
138
|
+
const results = [];
|
|
139
|
+
for (const peerId of peerIds) {
|
|
140
|
+
const info = await this.sendFileToPeer(peerId, blob, options);
|
|
141
|
+
results.push(info);
|
|
123
142
|
}
|
|
143
|
+
return results;
|
|
124
144
|
}
|
|
125
145
|
/**
|
|
126
|
-
*
|
|
146
|
+
* Start capturing local audio and bind it to current peer connections.
|
|
127
147
|
*/
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
148
|
+
async startVoice() {
|
|
149
|
+
if (this.localAudioStream && this.localAudioTrack) {
|
|
150
|
+
this.emitLocalAudioState();
|
|
151
|
+
return this.localAudioStream;
|
|
152
|
+
}
|
|
153
|
+
if (typeof navigator === "undefined" ||
|
|
154
|
+
!navigator.mediaDevices ||
|
|
155
|
+
typeof navigator.mediaDevices.getUserMedia !== "function") {
|
|
156
|
+
throw new Error("Audio capture is not available in this environment");
|
|
157
|
+
}
|
|
158
|
+
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
|
159
|
+
const [track] = stream.getAudioTracks();
|
|
160
|
+
if (!track) {
|
|
161
|
+
throw new Error("No audio track available from getUserMedia");
|
|
162
|
+
}
|
|
163
|
+
track.enabled = !this.isMuted;
|
|
164
|
+
this.localAudioStream = stream;
|
|
165
|
+
this.localAudioTrack = track;
|
|
166
|
+
await Promise.all(this.getActivePeers().map((peerId) => this.syncLocalAudioTrack(peerId)));
|
|
167
|
+
this.emitLocalAudioState();
|
|
168
|
+
return stream;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Stop local audio capture and detach it from active peers.
|
|
172
|
+
*/
|
|
173
|
+
stopVoice() {
|
|
174
|
+
if (this.localAudioTrack) {
|
|
175
|
+
this.audioSenders.forEach((sender, peerId) => {
|
|
176
|
+
if (sender && typeof sender.replaceTrack === "function") {
|
|
177
|
+
void sender.replaceTrack(null);
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
this.localAudioTrack.stop();
|
|
132
181
|
}
|
|
182
|
+
if (this.localAudioStream) {
|
|
183
|
+
this.localAudioStream.getTracks().forEach((track) => {
|
|
184
|
+
if (track.readyState !== "ended") {
|
|
185
|
+
track.stop();
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
this.localAudioTrack = null;
|
|
190
|
+
this.localAudioStream = null;
|
|
191
|
+
this.emitLocalAudioState();
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Toggle local mute state.
|
|
195
|
+
*/
|
|
196
|
+
setMuted(muted) {
|
|
197
|
+
this.isMuted = muted;
|
|
198
|
+
if (this.localAudioTrack) {
|
|
199
|
+
this.localAudioTrack.enabled = !muted;
|
|
200
|
+
}
|
|
201
|
+
this.emitLocalAudioState();
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Read current local audio state.
|
|
205
|
+
*/
|
|
206
|
+
getLocalAudioState() {
|
|
207
|
+
return {
|
|
208
|
+
active: !!this.localAudioTrack,
|
|
209
|
+
muted: this.isMuted,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Read current remote audio stream for a peer.
|
|
214
|
+
*/
|
|
215
|
+
getRemoteAudioStream(peerId) {
|
|
216
|
+
return this.remoteAudioStreams.get(peerId) ?? null;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Register a callback for ICE candidates from the specified peer.
|
|
220
|
+
*/
|
|
221
|
+
onIceCandidate(peerId, callback) {
|
|
222
|
+
const pc = this.getPeerConnection(peerId);
|
|
133
223
|
if (!this.iceCandidateCallbacks.has(peerId)) {
|
|
134
224
|
this.iceCandidateCallbacks.set(peerId, new Set());
|
|
135
225
|
}
|
|
136
226
|
this.iceCandidateCallbacks.get(peerId).add(callback);
|
|
137
227
|
pc.onicecandidate = (event) => {
|
|
138
|
-
if (event.candidate) {
|
|
139
|
-
|
|
140
|
-
if (callbacks) {
|
|
141
|
-
callbacks.forEach((cb) => cb(event.candidate.toJSON()));
|
|
142
|
-
}
|
|
228
|
+
if (!event.candidate) {
|
|
229
|
+
return;
|
|
143
230
|
}
|
|
231
|
+
const callbacks = this.iceCandidateCallbacks.get(peerId);
|
|
232
|
+
callbacks?.forEach((cb) => cb(event.candidate.toJSON()));
|
|
144
233
|
};
|
|
145
234
|
}
|
|
146
235
|
/**
|
|
147
|
-
* Register a callback for connection state changes
|
|
236
|
+
* Register a callback for connection state changes.
|
|
148
237
|
*/
|
|
149
238
|
onConnectionStateChange(peerId, callback) {
|
|
150
239
|
if (!this.connectionStateCallbacks.has(peerId)) {
|
|
@@ -153,7 +242,7 @@ class WebRTCManager {
|
|
|
153
242
|
this.connectionStateCallbacks.get(peerId).add(callback);
|
|
154
243
|
}
|
|
155
244
|
/**
|
|
156
|
-
* Register a callback for DataChannel state changes
|
|
245
|
+
* Register a callback for main DataChannel state changes.
|
|
157
246
|
*/
|
|
158
247
|
onDataChannelStateChange(peerId, callback) {
|
|
159
248
|
if (!this.dataChannelStateCallbacks.has(peerId)) {
|
|
@@ -162,147 +251,548 @@ class WebRTCManager {
|
|
|
162
251
|
this.dataChannelStateCallbacks.get(peerId).add(callback);
|
|
163
252
|
}
|
|
164
253
|
/**
|
|
165
|
-
* Register a callback for incoming messages
|
|
254
|
+
* Register a callback for incoming user messages.
|
|
166
255
|
*/
|
|
167
256
|
onMessage(callback) {
|
|
168
257
|
this.messageCallbacks.add(callback);
|
|
169
258
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
*/
|
|
173
|
-
setupDataChannel(peerId, dataChannel) {
|
|
174
|
-
this.dataChannels.set(peerId, dataChannel);
|
|
175
|
-
dataChannel.onopen = () => {
|
|
176
|
-
const callbacks = this.dataChannelStateCallbacks.get(peerId);
|
|
177
|
-
if (callbacks) {
|
|
178
|
-
callbacks.forEach((callback) => callback(dataChannel.readyState));
|
|
179
|
-
}
|
|
180
|
-
};
|
|
181
|
-
dataChannel.onclose = () => {
|
|
182
|
-
const callbacks = this.dataChannelStateCallbacks.get(peerId);
|
|
183
|
-
if (callbacks) {
|
|
184
|
-
callbacks.forEach((callback) => callback(dataChannel.readyState));
|
|
185
|
-
}
|
|
186
|
-
this.dataChannels.delete(peerId);
|
|
187
|
-
};
|
|
188
|
-
dataChannel.onerror = (error) => {
|
|
189
|
-
console.error(`DataChannel error with ${peerId}:`, error);
|
|
190
|
-
};
|
|
191
|
-
dataChannel.onmessage = (event) => {
|
|
192
|
-
try {
|
|
193
|
-
// Deserialize JSON message
|
|
194
|
-
const message = JSON.parse(event.data);
|
|
195
|
-
this.messageCallbacks.forEach((callback) => callback(peerId, message));
|
|
196
|
-
}
|
|
197
|
-
catch (error) {
|
|
198
|
-
// Log error but don't interrupt connection
|
|
199
|
-
console.error(`Failed to parse message from ${peerId}:`, error);
|
|
200
|
-
}
|
|
201
|
-
};
|
|
259
|
+
onFileTransferStarted(callback) {
|
|
260
|
+
this.fileTransferStartedCallbacks.add(callback);
|
|
202
261
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
* Throws error if any DataChannel is not ready
|
|
206
|
-
*/
|
|
207
|
-
sendMessage(message) {
|
|
208
|
-
const errors = [];
|
|
209
|
-
this.dataChannels.forEach((dataChannel, peerId) => {
|
|
210
|
-
if (dataChannel.readyState === "open") {
|
|
211
|
-
try {
|
|
212
|
-
// Serialize message to JSON
|
|
213
|
-
const serialized = JSON.stringify(message);
|
|
214
|
-
dataChannel.send(serialized);
|
|
215
|
-
}
|
|
216
|
-
catch (error) {
|
|
217
|
-
console.error(`Failed to send message to ${peerId}:`, error);
|
|
218
|
-
errors.push(peerId);
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
else {
|
|
222
|
-
errors.push(peerId);
|
|
223
|
-
}
|
|
224
|
-
});
|
|
225
|
-
if (errors.length > 0) {
|
|
226
|
-
throw new Error(`DataChannel not ready for peers: ${errors.join(", ")}`);
|
|
227
|
-
}
|
|
262
|
+
onFileTransferProgress(callback) {
|
|
263
|
+
this.fileTransferProgressCallbacks.add(callback);
|
|
228
264
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
}
|
|
241
|
-
try {
|
|
242
|
-
// Serialize message to JSON
|
|
243
|
-
const serialized = JSON.stringify(message);
|
|
244
|
-
dataChannel.send(serialized);
|
|
245
|
-
}
|
|
246
|
-
catch (error) {
|
|
247
|
-
console.error(`Failed to send message to ${peerId}:`, error);
|
|
248
|
-
throw error;
|
|
249
|
-
}
|
|
265
|
+
onFileTransferCompleted(callback) {
|
|
266
|
+
this.fileTransferCompletedCallbacks.add(callback);
|
|
267
|
+
}
|
|
268
|
+
onFileTransferFailed(callback) {
|
|
269
|
+
this.fileTransferFailedCallbacks.add(callback);
|
|
270
|
+
}
|
|
271
|
+
onRemoteAudioTrack(callback) {
|
|
272
|
+
this.remoteAudioTrackCallbacks.add(callback);
|
|
273
|
+
}
|
|
274
|
+
onLocalAudioStateChange(callback) {
|
|
275
|
+
this.localAudioStateCallbacks.add(callback);
|
|
250
276
|
}
|
|
251
277
|
/**
|
|
252
|
-
* Close the connection with a specific peer
|
|
278
|
+
* Close the connection with a specific peer.
|
|
253
279
|
*/
|
|
254
280
|
closePeerConnection(peerId) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
281
|
+
this.failActiveTransfers(peerId, new Error(`Peer connection closed for ${peerId}`));
|
|
282
|
+
const channels = this.normalizePeerChannels(this.dataChannels.get(peerId));
|
|
283
|
+
channels?.message?.close();
|
|
284
|
+
channels?.file?.close();
|
|
285
|
+
this.dataChannels.delete(peerId);
|
|
260
286
|
const pc = this.peerConnections.get(peerId);
|
|
261
287
|
if (pc) {
|
|
262
288
|
pc.close();
|
|
263
289
|
this.peerConnections.delete(peerId);
|
|
264
290
|
}
|
|
265
|
-
|
|
291
|
+
this.clearReadyResolver(peerId);
|
|
292
|
+
this.clearCompletionResolver(peerId);
|
|
293
|
+
this.outgoingTransfers.delete(peerId);
|
|
294
|
+
this.incomingTransfers.delete(peerId);
|
|
295
|
+
this.audioSenders.delete(peerId);
|
|
296
|
+
this.remoteAudioStreams.delete(peerId);
|
|
266
297
|
this.connectionStateCallbacks.delete(peerId);
|
|
267
298
|
this.dataChannelStateCallbacks.delete(peerId);
|
|
268
299
|
this.iceCandidateCallbacks.delete(peerId);
|
|
269
300
|
}
|
|
270
301
|
/**
|
|
271
|
-
* Close all connections and clean up resources
|
|
302
|
+
* Close all connections and clean up resources.
|
|
272
303
|
*/
|
|
273
304
|
closeAll() {
|
|
274
|
-
this.
|
|
275
|
-
|
|
276
|
-
});
|
|
277
|
-
this.dataChannels.clear();
|
|
278
|
-
this.peerConnections.forEach((pc) => {
|
|
279
|
-
pc.close();
|
|
305
|
+
this.getActivePeers().forEach((peerId) => {
|
|
306
|
+
this.closePeerConnection(peerId);
|
|
280
307
|
});
|
|
281
|
-
this.
|
|
308
|
+
this.stopVoice();
|
|
309
|
+
}
|
|
310
|
+
destroy() {
|
|
311
|
+
this.closeAll();
|
|
282
312
|
this.messageCallbacks.clear();
|
|
283
|
-
this.
|
|
284
|
-
this.
|
|
285
|
-
this.
|
|
313
|
+
this.fileTransferStartedCallbacks.clear();
|
|
314
|
+
this.fileTransferProgressCallbacks.clear();
|
|
315
|
+
this.fileTransferCompletedCallbacks.clear();
|
|
316
|
+
this.fileTransferFailedCallbacks.clear();
|
|
317
|
+
this.remoteAudioTrackCallbacks.clear();
|
|
318
|
+
this.localAudioStateCallbacks.clear();
|
|
286
319
|
}
|
|
287
320
|
/**
|
|
288
|
-
* Get all active peer IDs
|
|
321
|
+
* Get all active peer IDs.
|
|
289
322
|
*/
|
|
290
323
|
getActivePeers() {
|
|
291
324
|
return Array.from(this.peerConnections.keys());
|
|
292
325
|
}
|
|
293
326
|
/**
|
|
294
|
-
* Check if connected to a specific peer
|
|
327
|
+
* Check if connected to a specific peer.
|
|
295
328
|
*/
|
|
296
329
|
isConnected(peerId) {
|
|
297
330
|
const pc = this.peerConnections.get(peerId);
|
|
298
331
|
return pc?.connectionState === "connected";
|
|
299
332
|
}
|
|
300
333
|
/**
|
|
301
|
-
* Check if DataChannel is ready for a specific peer
|
|
334
|
+
* Check if the main DataChannel is ready for a specific peer.
|
|
302
335
|
*/
|
|
303
336
|
isDataChannelReady(peerId) {
|
|
304
|
-
|
|
305
|
-
|
|
337
|
+
return (this.normalizePeerChannels(this.dataChannels.get(peerId)).message
|
|
338
|
+
?.readyState === "open");
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Check if the file channel is ready for a specific peer.
|
|
342
|
+
*/
|
|
343
|
+
isFileChannelReady(peerId) {
|
|
344
|
+
return (this.normalizePeerChannels(this.dataChannels.get(peerId)).file
|
|
345
|
+
?.readyState === "open");
|
|
346
|
+
}
|
|
347
|
+
setupPeerConnection(peerId, pc) {
|
|
348
|
+
pc.onconnectionstatechange = () => {
|
|
349
|
+
const callbacks = this.connectionStateCallbacks.get(peerId);
|
|
350
|
+
callbacks?.forEach((callback) => callback(pc.connectionState));
|
|
351
|
+
if (pc.connectionState === "failed" ||
|
|
352
|
+
pc.connectionState === "closed" ||
|
|
353
|
+
pc.connectionState === "disconnected") {
|
|
354
|
+
this.closePeerConnection(peerId);
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
pc.ontrack = (event) => {
|
|
358
|
+
if (event.track.kind !== "audio") {
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
const stream = event.streams[0] ??
|
|
362
|
+
(typeof MediaStream !== "undefined"
|
|
363
|
+
? new MediaStream([event.track])
|
|
364
|
+
: null);
|
|
365
|
+
this.remoteAudioStreams.set(peerId, stream);
|
|
366
|
+
this.remoteAudioTrackCallbacks.forEach((callback) => callback(peerId, stream, event.track));
|
|
367
|
+
};
|
|
368
|
+
this.audioSenders.set(peerId, this.createAudioSender(pc));
|
|
369
|
+
void this.syncLocalAudioTrack(peerId);
|
|
370
|
+
}
|
|
371
|
+
createAudioSender(pc) {
|
|
372
|
+
const transceiverCapable = pc;
|
|
373
|
+
if (typeof transceiverCapable.addTransceiver === "function") {
|
|
374
|
+
const transceiver = transceiverCapable.addTransceiver("audio", {
|
|
375
|
+
direction: "sendrecv",
|
|
376
|
+
});
|
|
377
|
+
return transceiver.sender;
|
|
378
|
+
}
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
async syncLocalAudioTrack(peerId) {
|
|
382
|
+
const pc = this.peerConnections.get(peerId);
|
|
383
|
+
if (!pc) {
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
let sender = this.audioSenders.get(peerId) ?? null;
|
|
387
|
+
if (sender && typeof sender.replaceTrack === "function") {
|
|
388
|
+
await sender.replaceTrack(this.localAudioTrack);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (this.localAudioTrack &&
|
|
392
|
+
typeof pc.addTrack === "function") {
|
|
393
|
+
const addTrackCapable = pc;
|
|
394
|
+
const stream = this.localAudioStream ??
|
|
395
|
+
(typeof MediaStream !== "undefined"
|
|
396
|
+
? new MediaStream([this.localAudioTrack])
|
|
397
|
+
: undefined);
|
|
398
|
+
sender = stream
|
|
399
|
+
? addTrackCapable.addTrack(this.localAudioTrack, stream)
|
|
400
|
+
: addTrackCapable.addTrack(this.localAudioTrack);
|
|
401
|
+
this.audioSenders.set(peerId, sender);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
ensureDataChannel(peerId, pc, label) {
|
|
405
|
+
const channels = this.dataChannels.get(peerId) ?? {};
|
|
406
|
+
const kind = label === FILE_CHANNEL_LABEL ? "file" : "message";
|
|
407
|
+
const existing = channels[kind];
|
|
408
|
+
if (existing) {
|
|
409
|
+
return existing;
|
|
410
|
+
}
|
|
411
|
+
const channel = pc.createDataChannel(label);
|
|
412
|
+
this.setupDataChannel(peerId, channel);
|
|
413
|
+
return channel;
|
|
414
|
+
}
|
|
415
|
+
setupDataChannel(peerId, dataChannel) {
|
|
416
|
+
const kind = dataChannel.label === FILE_CHANNEL_LABEL ? "file" : "message";
|
|
417
|
+
const channels = this.normalizePeerChannels(this.dataChannels.get(peerId));
|
|
418
|
+
channels[kind] = dataChannel;
|
|
419
|
+
this.dataChannels.set(peerId, channels);
|
|
420
|
+
if (kind === "file") {
|
|
421
|
+
dataChannel.binaryType = "arraybuffer";
|
|
422
|
+
}
|
|
423
|
+
dataChannel.onopen = () => {
|
|
424
|
+
if (kind !== "message") {
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
const callbacks = this.dataChannelStateCallbacks.get(peerId);
|
|
428
|
+
callbacks?.forEach((callback) => callback(dataChannel.readyState));
|
|
429
|
+
};
|
|
430
|
+
dataChannel.onclose = () => {
|
|
431
|
+
if (kind === "message") {
|
|
432
|
+
const callbacks = this.dataChannelStateCallbacks.get(peerId);
|
|
433
|
+
callbacks?.forEach((callback) => callback(dataChannel.readyState));
|
|
434
|
+
}
|
|
435
|
+
const storedChannels = this.dataChannels.get(peerId);
|
|
436
|
+
if (storedChannels && this.isPeerChannels(storedChannels) && storedChannels[kind] === dataChannel) {
|
|
437
|
+
delete storedChannels[kind];
|
|
438
|
+
if (!storedChannels.message && !storedChannels.file) {
|
|
439
|
+
this.dataChannels.delete(peerId);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
if (kind === "message" || kind === "file") {
|
|
443
|
+
this.failActiveTransfers(peerId, new Error(`${kind} channel closed during file transfer`));
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
dataChannel.onerror = (error) => {
|
|
447
|
+
console.error(`DataChannel error with ${peerId}:`, error);
|
|
448
|
+
const transfer = kind === "file"
|
|
449
|
+
? this.outgoingTransfers.get(peerId) ?? this.incomingTransfers.get(peerId) ?? null
|
|
450
|
+
: null;
|
|
451
|
+
if (transfer) {
|
|
452
|
+
this.emitFileTransferFailed(peerId, transfer, new Error(`DataChannel error on ${kind} channel`));
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
dataChannel.onmessage = (event) => {
|
|
456
|
+
if (kind === "file") {
|
|
457
|
+
this.handleFileChunk(peerId, event.data);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
this.handleMessageChannelMessage(peerId, event.data);
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
handleMessageChannelMessage(peerId, rawData) {
|
|
464
|
+
try {
|
|
465
|
+
const message = JSON.parse(rawData);
|
|
466
|
+
if (this.isFileControlMessage(message)) {
|
|
467
|
+
this.handleFileControlMessage(peerId, message);
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
this.messageCallbacks.forEach((callback) => callback(peerId, message));
|
|
471
|
+
}
|
|
472
|
+
catch (error) {
|
|
473
|
+
console.error(`Failed to parse message from ${peerId}:`, error);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
async sendFileToPeer(peerId, blob, options) {
|
|
477
|
+
const messageChannel = this.getMessageChannel(peerId);
|
|
478
|
+
const fileChannel = this.getFileChannel(peerId);
|
|
479
|
+
if (messageChannel.readyState !== "open") {
|
|
480
|
+
throw new Error(`DataChannel not ready for ${peerId}`);
|
|
481
|
+
}
|
|
482
|
+
if (fileChannel.readyState !== "open") {
|
|
483
|
+
throw new Error(`File channel not ready for ${peerId}`);
|
|
484
|
+
}
|
|
485
|
+
if (this.outgoingTransfers.has(peerId)) {
|
|
486
|
+
throw new Error(`A file transfer is already active for ${peerId}`);
|
|
487
|
+
}
|
|
488
|
+
const transfer = {
|
|
489
|
+
transferId: this.generateTransferId(),
|
|
490
|
+
peerId,
|
|
491
|
+
direction: "send",
|
|
492
|
+
name: options.fileName || this.getBlobName(blob),
|
|
493
|
+
size: blob.size,
|
|
494
|
+
mimeType: options.mimeType || blob.type || "application/octet-stream",
|
|
495
|
+
lastModified: options.lastModified ?? this.getBlobLastModified(blob) ?? Date.now(),
|
|
496
|
+
blob,
|
|
497
|
+
chunkSize: options.chunkSize ?? this.fileChunkSize,
|
|
498
|
+
};
|
|
499
|
+
transfer.chunkSize = this.validateChunkSize(transfer.chunkSize);
|
|
500
|
+
this.outgoingTransfers.set(peerId, transfer);
|
|
501
|
+
this.emitFileTransferStarted(peerId, transfer);
|
|
502
|
+
this.emitFileTransferProgress(peerId, transfer, 0);
|
|
503
|
+
try {
|
|
504
|
+
const readyPromise = this.awaitTransferReady(peerId, transfer.transferId);
|
|
505
|
+
this.sendFileControl(peerId, {
|
|
506
|
+
__aves: FILE_PROTOCOL,
|
|
507
|
+
kind: "file-meta",
|
|
508
|
+
transfer: {
|
|
509
|
+
transferId: transfer.transferId,
|
|
510
|
+
name: transfer.name,
|
|
511
|
+
size: transfer.size,
|
|
512
|
+
mimeType: transfer.mimeType,
|
|
513
|
+
lastModified: transfer.lastModified,
|
|
514
|
+
},
|
|
515
|
+
});
|
|
516
|
+
await readyPromise;
|
|
517
|
+
let offset = 0;
|
|
518
|
+
while (offset < transfer.size) {
|
|
519
|
+
const nextChunk = transfer.blob.slice(offset, offset + transfer.chunkSize);
|
|
520
|
+
const buffer = await nextChunk.arrayBuffer();
|
|
521
|
+
fileChannel.send(buffer);
|
|
522
|
+
offset += buffer.byteLength;
|
|
523
|
+
this.emitFileTransferProgress(peerId, transfer, offset);
|
|
524
|
+
}
|
|
525
|
+
const completionPromise = this.awaitTransferCompletion(peerId, transfer.transferId);
|
|
526
|
+
fileChannel.send(`${FILE_END_MARKER_PREFIX}${transfer.transferId}`);
|
|
527
|
+
await completionPromise;
|
|
528
|
+
const result = {
|
|
529
|
+
...transfer,
|
|
530
|
+
};
|
|
531
|
+
this.fileTransferCompletedCallbacks.forEach((callback) => callback(peerId, result));
|
|
532
|
+
return transfer;
|
|
533
|
+
}
|
|
534
|
+
catch (error) {
|
|
535
|
+
const transferError = error instanceof Error ? error : new Error("File transfer failed");
|
|
536
|
+
this.sendFileControl(peerId, {
|
|
537
|
+
__aves: FILE_PROTOCOL,
|
|
538
|
+
kind: "file-error",
|
|
539
|
+
transferId: transfer.transferId,
|
|
540
|
+
message: transferError.message,
|
|
541
|
+
});
|
|
542
|
+
this.emitFileTransferFailed(peerId, transfer, transferError);
|
|
543
|
+
throw transferError;
|
|
544
|
+
}
|
|
545
|
+
finally {
|
|
546
|
+
this.clearReadyResolver(peerId);
|
|
547
|
+
this.clearCompletionResolver(peerId);
|
|
548
|
+
this.outgoingTransfers.delete(peerId);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
handleFileControlMessage(peerId, message) {
|
|
552
|
+
switch (message.kind) {
|
|
553
|
+
case "file-meta": {
|
|
554
|
+
const transfer = {
|
|
555
|
+
transferId: message.transfer.transferId,
|
|
556
|
+
peerId,
|
|
557
|
+
direction: "receive",
|
|
558
|
+
name: message.transfer.name,
|
|
559
|
+
size: message.transfer.size,
|
|
560
|
+
mimeType: message.transfer.mimeType,
|
|
561
|
+
lastModified: message.transfer.lastModified,
|
|
562
|
+
chunks: [],
|
|
563
|
+
bytesTransferred: 0,
|
|
564
|
+
};
|
|
565
|
+
this.incomingTransfers.set(peerId, transfer);
|
|
566
|
+
this.emitFileTransferStarted(peerId, transfer);
|
|
567
|
+
this.emitFileTransferProgress(peerId, transfer, 0);
|
|
568
|
+
this.sendFileControl(peerId, {
|
|
569
|
+
__aves: FILE_PROTOCOL,
|
|
570
|
+
kind: "file-ready",
|
|
571
|
+
transferId: transfer.transferId,
|
|
572
|
+
});
|
|
573
|
+
break;
|
|
574
|
+
}
|
|
575
|
+
case "file-ready": {
|
|
576
|
+
const resolver = this.readyResolvers.get(peerId);
|
|
577
|
+
if (resolver && resolver.transferId === message.transferId) {
|
|
578
|
+
clearTimeout(resolver.timeoutId);
|
|
579
|
+
this.readyResolvers.delete(peerId);
|
|
580
|
+
resolver.resolve();
|
|
581
|
+
}
|
|
582
|
+
break;
|
|
583
|
+
}
|
|
584
|
+
case "file-complete": {
|
|
585
|
+
const resolver = this.completionResolvers.get(peerId);
|
|
586
|
+
if (resolver && resolver.transferId === message.transferId) {
|
|
587
|
+
clearTimeout(resolver.timeoutId);
|
|
588
|
+
this.completionResolvers.delete(peerId);
|
|
589
|
+
resolver.resolve();
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
case "file-error": {
|
|
595
|
+
const transfer = this.outgoingTransfers.get(peerId) ??
|
|
596
|
+
this.incomingTransfers.get(peerId) ??
|
|
597
|
+
null;
|
|
598
|
+
this.emitFileTransferFailed(peerId, transfer, new Error(message.message));
|
|
599
|
+
this.outgoingTransfers.delete(peerId);
|
|
600
|
+
this.incomingTransfers.delete(peerId);
|
|
601
|
+
this.clearReadyResolver(peerId);
|
|
602
|
+
this.clearCompletionResolver(peerId);
|
|
603
|
+
break;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
handleFileChunk(peerId, data) {
|
|
608
|
+
const transfer = this.incomingTransfers.get(peerId);
|
|
609
|
+
if (!transfer) {
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (typeof data === "string" &&
|
|
613
|
+
data === `${FILE_END_MARKER_PREFIX}${transfer.transferId}`) {
|
|
614
|
+
const result = {
|
|
615
|
+
transferId: transfer.transferId,
|
|
616
|
+
peerId,
|
|
617
|
+
direction: "receive",
|
|
618
|
+
name: transfer.name,
|
|
619
|
+
size: transfer.size,
|
|
620
|
+
mimeType: transfer.mimeType,
|
|
621
|
+
lastModified: transfer.lastModified,
|
|
622
|
+
blob: new Blob(transfer.chunks, { type: transfer.mimeType }),
|
|
623
|
+
};
|
|
624
|
+
this.fileTransferCompletedCallbacks.forEach((callback) => callback(peerId, result));
|
|
625
|
+
this.sendFileControl(peerId, {
|
|
626
|
+
__aves: FILE_PROTOCOL,
|
|
627
|
+
kind: "file-complete",
|
|
628
|
+
transferId: transfer.transferId,
|
|
629
|
+
});
|
|
630
|
+
this.incomingTransfers.delete(peerId);
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
transfer.chunks.push(data);
|
|
634
|
+
transfer.bytesTransferred += this.getChunkSize(data);
|
|
635
|
+
this.emitFileTransferProgress(peerId, transfer, transfer.bytesTransferred);
|
|
636
|
+
}
|
|
637
|
+
emitFileTransferStarted(peerId, info) {
|
|
638
|
+
this.fileTransferStartedCallbacks.forEach((callback) => callback(peerId, info));
|
|
639
|
+
}
|
|
640
|
+
emitFileTransferProgress(peerId, info, bytesTransferred) {
|
|
641
|
+
const progress = {
|
|
642
|
+
...info,
|
|
643
|
+
bytesTransferred: Math.min(bytesTransferred, info.size),
|
|
644
|
+
progress: info.size === 0
|
|
645
|
+
? 100
|
|
646
|
+
: Math.min(100, (bytesTransferred / info.size) * 100),
|
|
647
|
+
};
|
|
648
|
+
this.fileTransferProgressCallbacks.forEach((callback) => callback(peerId, progress));
|
|
649
|
+
}
|
|
650
|
+
emitFileTransferFailed(peerId, info, error) {
|
|
651
|
+
this.fileTransferFailedCallbacks.forEach((callback) => callback(peerId, info, error));
|
|
652
|
+
}
|
|
653
|
+
emitLocalAudioState() {
|
|
654
|
+
const state = this.getLocalAudioState();
|
|
655
|
+
this.localAudioStateCallbacks.forEach((callback) => callback(state));
|
|
656
|
+
}
|
|
657
|
+
sendFileControl(peerId, message) {
|
|
658
|
+
const dataChannel = this.getMessageChannel(peerId);
|
|
659
|
+
dataChannel.send(JSON.stringify(message));
|
|
660
|
+
}
|
|
661
|
+
awaitTransferReady(peerId, transferId) {
|
|
662
|
+
return new Promise((resolve, reject) => {
|
|
663
|
+
const timeoutId = setTimeout(() => {
|
|
664
|
+
this.readyResolvers.delete(peerId);
|
|
665
|
+
reject(new Error("Timed out waiting for file receiver readiness"));
|
|
666
|
+
}, FILE_READY_TIMEOUT_MS);
|
|
667
|
+
this.readyResolvers.set(peerId, {
|
|
668
|
+
transferId,
|
|
669
|
+
resolve,
|
|
670
|
+
reject,
|
|
671
|
+
timeoutId,
|
|
672
|
+
});
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
clearReadyResolver(peerId) {
|
|
676
|
+
const resolver = this.readyResolvers.get(peerId);
|
|
677
|
+
if (!resolver) {
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
clearTimeout(resolver.timeoutId);
|
|
681
|
+
this.readyResolvers.delete(peerId);
|
|
682
|
+
}
|
|
683
|
+
awaitTransferCompletion(peerId, transferId) {
|
|
684
|
+
return new Promise((resolve, reject) => {
|
|
685
|
+
const timeoutId = setTimeout(() => {
|
|
686
|
+
this.completionResolvers.delete(peerId);
|
|
687
|
+
reject(new Error("Timed out waiting for file receiver confirmation"));
|
|
688
|
+
}, FILE_COMPLETE_TIMEOUT_MS);
|
|
689
|
+
this.completionResolvers.set(peerId, {
|
|
690
|
+
transferId,
|
|
691
|
+
resolve,
|
|
692
|
+
reject,
|
|
693
|
+
timeoutId,
|
|
694
|
+
});
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
clearCompletionResolver(peerId) {
|
|
698
|
+
const resolver = this.completionResolvers.get(peerId);
|
|
699
|
+
if (!resolver) {
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
clearTimeout(resolver.timeoutId);
|
|
703
|
+
this.completionResolvers.delete(peerId);
|
|
704
|
+
}
|
|
705
|
+
getPeerConnection(peerId) {
|
|
706
|
+
const pc = this.peerConnections.get(peerId);
|
|
707
|
+
if (!pc) {
|
|
708
|
+
throw new Error(`No peer connection found for ${peerId}`);
|
|
709
|
+
}
|
|
710
|
+
return pc;
|
|
711
|
+
}
|
|
712
|
+
getMessageChannel(peerId) {
|
|
713
|
+
const channel = this.normalizePeerChannels(this.dataChannels.get(peerId)).message;
|
|
714
|
+
if (!channel) {
|
|
715
|
+
throw new Error(`No DataChannel found for ${peerId}`);
|
|
716
|
+
}
|
|
717
|
+
return channel;
|
|
718
|
+
}
|
|
719
|
+
getFileChannel(peerId) {
|
|
720
|
+
const channel = this.normalizePeerChannels(this.dataChannels.get(peerId)).file;
|
|
721
|
+
if (!channel) {
|
|
722
|
+
throw new Error(`No file channel found for ${peerId}`);
|
|
723
|
+
}
|
|
724
|
+
return channel;
|
|
725
|
+
}
|
|
726
|
+
isFileControlMessage(message) {
|
|
727
|
+
if (!message || typeof message !== "object") {
|
|
728
|
+
return false;
|
|
729
|
+
}
|
|
730
|
+
const record = message;
|
|
731
|
+
return record.__aves === FILE_PROTOCOL && typeof record.kind === "string";
|
|
732
|
+
}
|
|
733
|
+
getChunkSize(data) {
|
|
734
|
+
if (typeof data === "string") {
|
|
735
|
+
return data.length;
|
|
736
|
+
}
|
|
737
|
+
if (data instanceof ArrayBuffer) {
|
|
738
|
+
return data.byteLength;
|
|
739
|
+
}
|
|
740
|
+
return data.size;
|
|
741
|
+
}
|
|
742
|
+
getBlobName(blob) {
|
|
743
|
+
const fileBlob = blob;
|
|
744
|
+
return fileBlob.name || "shared-file";
|
|
745
|
+
}
|
|
746
|
+
getBlobLastModified(blob) {
|
|
747
|
+
const fileBlob = blob;
|
|
748
|
+
return typeof fileBlob.lastModified === "number"
|
|
749
|
+
? fileBlob.lastModified
|
|
750
|
+
: undefined;
|
|
751
|
+
}
|
|
752
|
+
generateTransferId() {
|
|
753
|
+
return `file-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
754
|
+
}
|
|
755
|
+
validateChunkSize(chunkSize) {
|
|
756
|
+
if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
|
|
757
|
+
throw new Error("chunkSize must be a positive integer");
|
|
758
|
+
}
|
|
759
|
+
return chunkSize;
|
|
760
|
+
}
|
|
761
|
+
failActiveTransfers(peerId, error) {
|
|
762
|
+
const outgoingTransfer = this.outgoingTransfers.get(peerId) ?? null;
|
|
763
|
+
const incomingTransfer = this.incomingTransfers.get(peerId) ?? null;
|
|
764
|
+
if (outgoingTransfer) {
|
|
765
|
+
this.emitFileTransferFailed(peerId, outgoingTransfer, error);
|
|
766
|
+
}
|
|
767
|
+
if (incomingTransfer) {
|
|
768
|
+
this.emitFileTransferFailed(peerId, incomingTransfer, error);
|
|
769
|
+
}
|
|
770
|
+
const readyResolver = this.readyResolvers.get(peerId);
|
|
771
|
+
if (readyResolver) {
|
|
772
|
+
readyResolver.reject(error);
|
|
773
|
+
this.clearReadyResolver(peerId);
|
|
774
|
+
}
|
|
775
|
+
const completionResolver = this.completionResolvers.get(peerId);
|
|
776
|
+
if (completionResolver) {
|
|
777
|
+
completionResolver.reject(error);
|
|
778
|
+
this.clearCompletionResolver(peerId);
|
|
779
|
+
}
|
|
780
|
+
this.outgoingTransfers.delete(peerId);
|
|
781
|
+
this.incomingTransfers.delete(peerId);
|
|
782
|
+
}
|
|
783
|
+
normalizePeerChannels(channels) {
|
|
784
|
+
if (!channels) {
|
|
785
|
+
return {};
|
|
786
|
+
}
|
|
787
|
+
if (this.isPeerChannels(channels)) {
|
|
788
|
+
return channels;
|
|
789
|
+
}
|
|
790
|
+
return {
|
|
791
|
+
message: channels,
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
isPeerChannels(value) {
|
|
795
|
+
return !("readyState" in value);
|
|
306
796
|
}
|
|
307
797
|
}
|
|
308
798
|
exports.WebRTCManager = WebRTCManager;
|