forked from Onek8/LNXSDK
525 lines
16 KiB
Haxe
525 lines
16 KiB
Haxe
package leenkx.network.torrent.peer;
|
|
|
|
import haxe.io.Bytes;
|
|
import leenkx.network.torrent.transport.RtcSignaling;
|
|
|
|
#if lnx_datachannel
|
|
import datachannel.RTC;
|
|
import datachannel.RTCPeerConnection.RTCState;
|
|
import datachannel.RTCPeerConnection.RTCGatheringState;
|
|
#elseif kha_krom
|
|
import leenkx.network.torrent.transport.RtcNative;
|
|
#elseif js
|
|
import js.html.rtc.PeerConnection;
|
|
import js.html.rtc.DataChannelEvent;
|
|
import js.html.rtc.IceConnectionState;
|
|
import js.html.rtc.IceGatheringState;
|
|
import js.html.rtc.SessionDescription;
|
|
import js.html.rtc.SdpType;
|
|
#end
|
|
|
|
class RtcPeerPool {
|
|
static inline var CHANNEL_LABEL = "bt-wire";
|
|
|
|
var channelLabel:String = CHANNEL_LABEL;
|
|
var unordered:Bool = false;
|
|
var maxRetransmits:Int = -1;
|
|
|
|
public var onPeerChannel:String -> IPeerChannel -> Void;
|
|
public var onPeerLeft:String -> Void;
|
|
public var onTrackerUpdate:Dynamic -> Void;
|
|
public var onReady:Void -> Void;
|
|
public var onError:String -> Void;
|
|
public var statsProvider:Void -> {downloaded:Float, uploaded:Float,
|
|
left:Float} = null;
|
|
|
|
var signalings:Array<RtcSignaling> = [];
|
|
var iceServers:Array<String>;
|
|
#if lnx_datachannel
|
|
var eventTimer:haxe.Timer = null;
|
|
#end
|
|
|
|
var peers:Map<String, Dynamic> = [];
|
|
var channels:Map<String, IPeerChannel> = [];
|
|
var offerPeers:Map<String, Dynamic> = [];
|
|
var offerChannels:Map<String, IPeerChannel> = [];
|
|
var offerPeerIds:Map<String, {v:String}> = [];
|
|
var promotedPeerIds:Map<String, String> = [];
|
|
|
|
#if kha_krom
|
|
var dcToOffer:Map<Int, String> = [];
|
|
var rtcInitialized = false;
|
|
#end
|
|
|
|
public static var defaultIceServers:Array<String> =
|
|
["stun:stun.l.google.com:19302", "stun:global.stun.twilio.com:3478"];
|
|
|
|
public function new(?iceServers:Array<String>, ?channelLabel:String, unordered:Bool = false, maxRetransmits:Int = -1) {
|
|
this.iceServers = iceServers != null ? iceServers
|
|
: defaultIceServers.copy();
|
|
if (channelLabel != null) this.channelLabel = channelLabel;
|
|
this.unordered = unordered;
|
|
this.maxRetransmits = maxRetransmits;
|
|
}
|
|
|
|
public function connect(trackerUrl:String, infoHashBinary:String, peerIdBinary:String):RtcSignaling {
|
|
leenkx.network.torrent.TorrentClient.initMain();
|
|
#if lnx_datachannel
|
|
RTC.init();
|
|
#end
|
|
#if kha_krom
|
|
if (!rtcInitialized) {
|
|
RtcNative.init();
|
|
rtcInitialized = true;
|
|
}
|
|
#end
|
|
|
|
var signaling = new RtcSignaling(trackerUrl, infoHashBinary, peerIdBinary);
|
|
signalings.push(signaling);
|
|
signaling.statsProvider = statsProvider;
|
|
signaling.onConnected = function() {
|
|
if (onReady != null) onReady();
|
|
};
|
|
signaling.onTrackerUpdate = function(d) {
|
|
if (onTrackerUpdate != null) onTrackerUpdate(d);
|
|
};
|
|
signaling.onCreateOffer = onCreateOffer;
|
|
signaling.onRemoteOffer = function(peerIdHex, offerIdHex, o) {
|
|
onRemoteOffer(signaling, peerIdHex, offerIdHex, o);
|
|
};
|
|
signaling.onRemoteAnswer = onRemoteAnswer;
|
|
signaling.onOfferTimeout = function(offerId) removeOfferPeer(offerId);
|
|
signaling.onPeerLeft = function(peerId) {
|
|
removePeer(peerId);
|
|
if (onPeerLeft != null) onPeerLeft(peerId);
|
|
};
|
|
signaling.onError = function(msg) {
|
|
if (onError != null) onError(msg);
|
|
};
|
|
signaling.start();
|
|
|
|
#if lnx_datachannel
|
|
if (eventTimer == null) {
|
|
eventTimer = new haxe.Timer(10);
|
|
eventTimer.run = function() RTC.processEvents();
|
|
}
|
|
#end
|
|
return signaling;
|
|
}
|
|
|
|
public function getPeerCount():Int {
|
|
return Lambda.count(channels);
|
|
}
|
|
|
|
public function close():Void {
|
|
#if lnx_datachannel
|
|
if (eventTimer != null) {
|
|
eventTimer.stop();
|
|
eventTimer = null;
|
|
}
|
|
#end
|
|
for (s in signalings) s.close();
|
|
signalings = [];
|
|
for (id in [for (k in offerPeers.keys()) k])
|
|
removeOfferPeer(id);
|
|
for (id in [for (k in peers.keys()) k]) removePeer(id);
|
|
#if kha_krom
|
|
dcToOffer.clear();
|
|
if (rtcInitialized) {
|
|
RtcNative.cleanup();
|
|
rtcInitialized = false;
|
|
}
|
|
#end
|
|
#if lnx_datachannel
|
|
RTC.finalize();
|
|
#end
|
|
}
|
|
|
|
function onCreateOffer(offerIdHex:String, cb:String -> Void):Void {
|
|
#if lnx_datachannel
|
|
var pc = new datachannel.RTCPeerConnection(iceServers, "0.0.0.0");
|
|
offerPeers.set(offerIdHex, pc);
|
|
offerPeerIds.set(offerIdHex, {v: null});
|
|
pc.onStateChange = function(state:RTCState) {
|
|
if (state == RTC_DISCONNECTED || state == RTC_FAILED
|
|
|| state == RTC_CLOSED) {
|
|
removeOfferPeer(offerIdHex);
|
|
}
|
|
};
|
|
var iceComplete = false;
|
|
var iceTimer:haxe.Timer = null;
|
|
var sendSdp = function() {
|
|
if (iceComplete) return;
|
|
iceComplete = true;
|
|
if (iceTimer != null) iceTimer.stop();
|
|
if (!offerPeers.exists(offerIdHex)) return;
|
|
cb(pc.getLocalDescription());
|
|
};
|
|
pc.onGatheringStateChange = function(state) {
|
|
if (state == RTC_GATHERING_COMPLETE) sendSdp();
|
|
};
|
|
var dc = pc.createDatachannelWithOptions(channelLabel, unordered,
|
|
maxRetransmits < 0 ? null : maxRetransmits, null);
|
|
attachOfferChannel(offerIdHex, new DataChannelPeer(dc));
|
|
pc.onLocalDescription = function(sdp, type) {
|
|
if (type == "offer") {
|
|
iceTimer = new haxe.Timer(5000);
|
|
iceTimer.run = sendSdp;
|
|
}
|
|
};
|
|
|
|
#elseif kha_krom
|
|
var pcId = RtcNative.createPeerConnection(iceServers);
|
|
offerPeers.set(offerIdHex, pcId);
|
|
offerPeerIds.set(offerIdHex, {v: null});
|
|
RtcNative.setStateChangeCallback(pcId, function(state:Int) {
|
|
if (state == RtcNative.RTC_DISCONNECTED
|
|
|| state == RtcNative.RTC_FAILED
|
|
|| state == RtcNative.RTC_CLOSED) {
|
|
removeOfferPeer(offerIdHex);
|
|
}
|
|
});
|
|
RtcNative.setDataChannelCallback(pcId, function(dcId:Int) {
|
|
dcToOffer.set(dcId, offerIdHex);
|
|
attachOfferChannel(offerIdHex, new DataChannelPeer(dcId));
|
|
});
|
|
var dcId = RtcNative.createDataChannel(pcId, channelLabel,
|
|
unordered, maxRetransmits);
|
|
dcToOffer.set(dcId, offerIdHex);
|
|
attachOfferChannel(offerIdHex, new DataChannelPeer(dcId));
|
|
var iceComplete = false;
|
|
var iceTimer:haxe.Timer = null;
|
|
var sendSdp = function() {
|
|
if (iceComplete) return;
|
|
iceComplete = true;
|
|
if (iceTimer != null) iceTimer.stop();
|
|
if (!offerPeers.exists(offerIdHex)) return;
|
|
cb(RtcNative.getLocalDescription(pcId));
|
|
};
|
|
RtcNative.setGatheringStateCallback(pcId, function(state:Int) {
|
|
if (state == RtcNative.RTC_GATHERING_COMPLETE) sendSdp();
|
|
});
|
|
RtcNative.setLocalDescriptionCallback(pcId,
|
|
function(sdp:String, type:String) {
|
|
if (type == "offer") {
|
|
iceTimer = new haxe.Timer(5000);
|
|
iceTimer.run = sendSdp;
|
|
}
|
|
});
|
|
|
|
#elseif js
|
|
var rtcConfig:Dynamic = {
|
|
iceServers: iceServers.map(function(s) return {urls: s}),
|
|
sdpSemantics: 'unified-plan'
|
|
};
|
|
var pc = new PeerConnection(rtcConfig);
|
|
offerPeers.set(offerIdHex, pc);
|
|
offerPeerIds.set(offerIdHex, {v: null});
|
|
pc.oniceconnectionstatechange = function(_) {
|
|
var state = pc.iceConnectionState;
|
|
if (state == IceConnectionState.FAILED
|
|
|| state == IceConnectionState.DISCONNECTED
|
|
|| state == IceConnectionState.CLOSED) {
|
|
removeOfferPeer(offerIdHex);
|
|
}
|
|
};
|
|
var dc = pc.createDataChannel(channelLabel,
|
|
{ordered: !unordered, maxRetransmits: unordered ? maxRetransmits : null});
|
|
attachOfferChannel(offerIdHex, new DataChannelPeer(dc));
|
|
var iceComplete = false;
|
|
var iceTimer:haxe.Timer = null;
|
|
var sendSdp = function() {
|
|
if (iceComplete) return;
|
|
iceComplete = true;
|
|
if (iceTimer != null) iceTimer.stop();
|
|
var localDesc = pc.localDescription;
|
|
cb(localDesc != null ? localDesc.sdp : null);
|
|
};
|
|
pc.onicegatheringstatechange = function(_) {
|
|
if (pc.iceGatheringState == IceGatheringState.COMPLETE) sendSdp();
|
|
};
|
|
pc.createOffer({}).then(function(offer) {
|
|
pc.setLocalDescription(offer).then(function(_) {
|
|
iceTimer = new haxe.Timer(5000);
|
|
iceTimer.run = sendSdp;
|
|
});
|
|
}, function(e) {
|
|
if (onError != null) onError("onCreateOffer: " + Std.string(e));
|
|
});
|
|
#end
|
|
}
|
|
|
|
function onRemoteOffer(sig:RtcSignaling, peerIdHex:String, offerIdHex:String, offer:Dynamic):Void {
|
|
var sdp:String = offer.sdp != null ? offer.sdp : offer;
|
|
#if lnx_datachannel
|
|
var pc = new datachannel.RTCPeerConnection(iceServers, "0.0.0.0");
|
|
offerPeers.set(offerIdHex, pc);
|
|
offerPeerIds.set(offerIdHex, {v: peerIdHex});
|
|
pc.onStateChange = function(state:RTCState) {
|
|
if (state == RTC_DISCONNECTED || state == RTC_FAILED
|
|
|| state == RTC_CLOSED) {
|
|
removeOfferPeer(offerIdHex);
|
|
}
|
|
};
|
|
pc.onDataChannel = function(dc) {
|
|
attachOfferChannel(offerIdHex, new DataChannelPeer(dc));
|
|
};
|
|
var iceComplete = false;
|
|
var iceTimer:haxe.Timer = null;
|
|
var sendAnswerSdp = function() {
|
|
if (iceComplete) return;
|
|
iceComplete = true;
|
|
if (iceTimer != null) iceTimer.stop();
|
|
if (!offerPeers.exists(offerIdHex)) return;
|
|
sig.sendAnswer(peerIdHex, offerIdHex, pc.getLocalDescription());
|
|
};
|
|
pc.onGatheringStateChange = function(state) {
|
|
if (state == RTC_GATHERING_COMPLETE) sendAnswerSdp();
|
|
};
|
|
pc.onLocalDescription = function(desc, type) {
|
|
if (type == "answer") {
|
|
iceTimer = new haxe.Timer(5000);
|
|
iceTimer.run = sendAnswerSdp;
|
|
}
|
|
};
|
|
try {
|
|
pc.setRemoteDescription(sdp, "offer");
|
|
} catch(e:Dynamic) {
|
|
removeOfferPeer(offerIdHex);
|
|
if (onError != null) onError("onRemoteOffer: " + Std.string(e));
|
|
}
|
|
|
|
#elseif kha_krom
|
|
var pcId = RtcNative.createPeerConnection(iceServers);
|
|
offerPeers.set(offerIdHex, pcId);
|
|
offerPeerIds.set(offerIdHex, {v: peerIdHex});
|
|
RtcNative.setStateChangeCallback(pcId, function(state:Int) {
|
|
if (state == RtcNative.RTC_DISCONNECTED
|
|
|| state == RtcNative.RTC_FAILED
|
|
|| state == RtcNative.RTC_CLOSED) {
|
|
removeOfferPeer(offerIdHex);
|
|
}
|
|
});
|
|
RtcNative.setDataChannelCallback(pcId, function(dcId:Int) {
|
|
dcToOffer.set(dcId, offerIdHex);
|
|
attachOfferChannel(offerIdHex, new DataChannelPeer(dcId));
|
|
});
|
|
var iceComplete = false;
|
|
var iceTimer:haxe.Timer = null;
|
|
var sendAnswerSdp = function() {
|
|
if (iceComplete) return;
|
|
iceComplete = true;
|
|
if (iceTimer != null) iceTimer.stop();
|
|
if (!offerPeers.exists(offerIdHex)) return;
|
|
sig.sendAnswer(peerIdHex, offerIdHex, RtcNative.getLocalDescription(pcId));
|
|
};
|
|
RtcNative.setGatheringStateCallback(pcId, function(state:Int) {
|
|
if (state == RtcNative.RTC_GATHERING_COMPLETE) sendAnswerSdp();
|
|
});
|
|
RtcNative.setLocalDescriptionCallback(pcId,
|
|
function(sdp:String, type:String) {
|
|
if (type == "answer") {
|
|
iceTimer = new haxe.Timer(5000);
|
|
iceTimer.run = sendAnswerSdp;
|
|
}
|
|
});
|
|
var srd = RtcNative.setRemoteDescription(pcId, sdp, "offer");
|
|
if (srd < 0) {
|
|
removeOfferPeer(offerIdHex);
|
|
if (onError != null) {
|
|
onError("onRemoteOffer: setRemoteDescription failed");
|
|
}
|
|
return;
|
|
}
|
|
|
|
#elseif js
|
|
var rtcConfig:Dynamic = {
|
|
iceServers: iceServers.map(function(s) return {urls: s}),
|
|
sdpSemantics: 'unified-plan'
|
|
};
|
|
var pc = new PeerConnection(rtcConfig);
|
|
offerPeers.set(offerIdHex, pc);
|
|
offerPeerIds.set(offerIdHex, {v: peerIdHex});
|
|
pc.oniceconnectionstatechange = function(_) {
|
|
var state = pc.iceConnectionState;
|
|
if (state == IceConnectionState.FAILED
|
|
|| state == IceConnectionState.DISCONNECTED
|
|
|| state == IceConnectionState.CLOSED) {
|
|
removeOfferPeer(offerIdHex);
|
|
}
|
|
};
|
|
pc.ondatachannel = function(e:DataChannelEvent) {
|
|
attachOfferChannel(offerIdHex, new DataChannelPeer(e.channel));
|
|
};
|
|
var iceComplete = false;
|
|
var iceTimer:haxe.Timer = null;
|
|
var sendAnswerSdp = function() {
|
|
if (iceComplete) return;
|
|
iceComplete = true;
|
|
if (iceTimer != null) iceTimer.stop();
|
|
var localDesc = pc.localDescription;
|
|
sig.sendAnswer(peerIdHex, offerIdHex,
|
|
localDesc != null ? localDesc.sdp : null);
|
|
};
|
|
pc.onicegatheringstatechange = function(_) {
|
|
if (pc.iceGatheringState == IceGatheringState.COMPLETE) {
|
|
sendAnswerSdp();
|
|
}
|
|
};
|
|
pc.setRemoteDescription(
|
|
new SessionDescription({type: SdpType.OFFER, sdp: sdp}))
|
|
.then(function(_) {
|
|
pc.createAnswer().then(function(answer) {
|
|
pc.setLocalDescription(answer).then(function(_) {
|
|
iceTimer = new haxe.Timer(5000);
|
|
iceTimer.run = sendAnswerSdp;
|
|
});
|
|
});
|
|
}, function(e) {
|
|
if (onError != null) onError("onRemoteOffer: " + Std.string(e));
|
|
});
|
|
#end
|
|
}
|
|
|
|
function onRemoteAnswer(peerIdHex:String, offerIdHex:String, answer:Dynamic):Void {
|
|
var sdp:String = answer.sdp != null ? answer.sdp : answer;
|
|
var box = offerPeerIds.get(offerIdHex);
|
|
if (box != null) box.v = peerIdHex;
|
|
var pc = offerPeers.get(offerIdHex);
|
|
if (pc == null) return;
|
|
#if lnx_datachannel
|
|
try {
|
|
pc.setRemoteDescription(sdp, "answer");
|
|
} catch(e:Dynamic) {
|
|
removeOfferPeer(offerIdHex);
|
|
if (onError != null) onError("onRemoteAnswer: " + Std.string(e));
|
|
return;
|
|
}
|
|
#elseif kha_krom
|
|
var srd = RtcNative.setRemoteDescription(pc, sdp, "answer");
|
|
if (srd < 0) {
|
|
removeOfferPeer(offerIdHex);
|
|
if (onError != null) {
|
|
onError("onRemoteAnswer: setRemoteDescription failed");
|
|
}
|
|
return;
|
|
}
|
|
#elseif js
|
|
pc.setRemoteDescription(
|
|
new SessionDescription({type: SdpType.ANSWER, sdp: sdp}))
|
|
.then(function(_) {
|
|
promoteOfferPeer(offerIdHex);
|
|
}, function(e) {
|
|
if (onError != null) onError("onRemoteAnswer: " + Std.string(e));
|
|
});
|
|
return;
|
|
#end
|
|
promoteOfferPeer(offerIdHex);
|
|
}
|
|
|
|
function attachOfferChannel(offerIdHex:String, ch:IPeerChannel):Void {
|
|
offerChannels.set(offerIdHex, ch);
|
|
var resolvedPeerId:String = null;
|
|
var fired = false;
|
|
ch.onOpen = function() {
|
|
var box = offerPeerIds.get(offerIdHex);
|
|
resolvedPeerId = box != null ? box.v : null;
|
|
if (resolvedPeerId == null) {
|
|
resolvedPeerId = promotedPeerIds.get(offerIdHex);
|
|
}
|
|
promoteOfferPeer(offerIdHex);
|
|
if (resolvedPeerId != null && !fired) {
|
|
fired = true;
|
|
firePeerChannel(resolvedPeerId, ch);
|
|
}
|
|
};
|
|
ch.onClose = function() {
|
|
offerChannels.remove(offerIdHex);
|
|
if (resolvedPeerId != null && channels.get(resolvedPeerId) == ch) {
|
|
removePeer(resolvedPeerId);
|
|
} else {
|
|
removeOfferPeer(offerIdHex);
|
|
}
|
|
};
|
|
if (ch.isOpen) ch.onOpen();
|
|
}
|
|
|
|
function firePeerChannel(peerId:String, ch:IPeerChannel):Void {
|
|
if (onPeerChannel != null) onPeerChannel(peerId, ch);
|
|
}
|
|
|
|
function promoteOfferPeer(offerIdHex:String):Void {
|
|
if (!offerPeers.exists(offerIdHex)) return;
|
|
var box = offerPeerIds.get(offerIdHex);
|
|
if (box == null || box.v == null) return;
|
|
var peerId = box.v;
|
|
if (peers.exists(peerId)) {
|
|
removeOfferPeer(offerIdHex);
|
|
return;
|
|
}
|
|
promotedPeerIds.set(offerIdHex, peerId);
|
|
var pc = offerPeers.get(offerIdHex);
|
|
var ch = offerChannels.get(offerIdHex);
|
|
peers.set(peerId, pc);
|
|
if (ch != null) channels.set(peerId, ch);
|
|
offerPeers.remove(offerIdHex);
|
|
offerChannels.remove(offerIdHex);
|
|
offerPeerIds.remove(offerIdHex);
|
|
#if kha_krom
|
|
for (dcId in [for (k in dcToOffer.keys()) k]) {
|
|
if (dcToOffer.get(dcId) == offerIdHex) {
|
|
dcToOffer.set(dcId, peerId);
|
|
}
|
|
}
|
|
#end
|
|
}
|
|
|
|
function removeOfferPeer(offerIdHex:String):Void {
|
|
var pc = offerPeers.get(offerIdHex);
|
|
if (pc != null) closePc(pc);
|
|
var ch = offerChannels.get(offerIdHex);
|
|
if (ch != null) ch.close();
|
|
offerPeers.remove(offerIdHex);
|
|
offerChannels.remove(offerIdHex);
|
|
offerPeerIds.remove(offerIdHex);
|
|
promotedPeerIds.remove(offerIdHex);
|
|
#if kha_krom
|
|
for (dcId in [for (k in dcToOffer.keys()) k]) {
|
|
if (dcToOffer.get(dcId) == offerIdHex) dcToOffer.remove(dcId);
|
|
}
|
|
#end
|
|
}
|
|
|
|
function removePeer(peerId:String):Void {
|
|
if (!peers.exists(peerId)) return;
|
|
closePc(peers.get(peerId));
|
|
var ch = channels.get(peerId);
|
|
if (ch != null) ch.close();
|
|
peers.remove(peerId);
|
|
channels.remove(peerId);
|
|
for (offerId in [for (k in promotedPeerIds.keys()) k]) {
|
|
if (promotedPeerIds.get(offerId) == peerId) {
|
|
promotedPeerIds.remove(offerId);
|
|
}
|
|
}
|
|
#if kha_krom
|
|
for (dcId in [for (k in dcToOffer.keys()) k]) {
|
|
if (dcToOffer.get(dcId) == peerId) dcToOffer.remove(dcId);
|
|
}
|
|
#end
|
|
}
|
|
|
|
function closePc(pc:Dynamic):Void {
|
|
#if lnx_datachannel
|
|
try pc.close() catch(e:Dynamic) {}
|
|
#elseif kha_krom
|
|
try {
|
|
RtcNative.closePeerConnection(pc);
|
|
RtcNative.deletePeerConnection(pc);
|
|
} catch(e:Dynamic) {}
|
|
#elseif js
|
|
try pc.close() catch(e:Dynamic) {}
|
|
#end
|
|
}
|
|
}
|