MWSE/script/index.js

1418 lines
49 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(() => {
class $d59cdc9b12df098b$export$98b66c25bb38499d {
constructor(mwse, options){
this.autoPair = false;
this.connected = false;
this.autoReconnect = true;
this.autoReconnectTimeout = 3000;
this.recaivePackEvent = [];
this.activeConnectionEvent = [];
this.passiveConnectionEvent = [];
if (options.endpoint == "auto") {
const RootURL = document.currentScript.src;
let scriptPath = new URL(RootURL);
let isSecurity = scriptPath.protocol == "https:";
let dumeUrl = scriptPath.pathname.split('/').slice(0, -1).join('/') + '/';
let wsSocket = new URL(dumeUrl, scriptPath);
wsSocket.protocol = isSecurity ? 'wss:' : 'ws:';
this.endpoint = new URL(wsSocket.href);
} else try {
// Testing
this.endpoint = new URL(options.endpoint);
} catch {
throw new Error("endpoint is required");
}
if (typeof options.autoReconnect == "boolean") this.autoReconnect = true;
else if (options.autoReconnect) {
this.autoReconnect = true;
this.autoReconnectTimeout = options.autoReconnect.timeout;
}
}
connect() {
if (this.autoReconnectTimer) clearTimeout(this.autoReconnectTimer);
this.ws = new WebSocket(this.endpoint.href);
this.addWSEvents();
}
disconnect() {
/**
* Eğer bilinerek elle kapatıldıysa otomatik tekrar bağlanmasının
* önüne geçmek için autoReconnect bayrağını her zaman kapalı tutmak gerekir
*/ this.autoReconnect = false;
this.ws.close();
}
addWSEvents() {
this.ws.addEventListener("open", ()=>this.eventOpen());
this.ws.addEventListener("close", ()=>this.eventClose());
this.ws.addEventListener("error", ()=>this.eventError());
this.ws.addEventListener("message", ({ data: data })=>this.eventMessage(data));
}
eventOpen() {
this.connected = true;
for (const callback of this.activeConnectionEvent)callback(void 0);
}
eventClose() {
for (const callback of this.passiveConnectionEvent)callback(void 0);
this.connected = false;
if (this.autoReconnect) this.autoReconnectTimer = setTimeout(()=>this.connect(), this.autoReconnectTimeout);
}
eventError() {
this.connected = false;
}
onRecaivePack(func) {
this.recaivePackEvent.push(func);
}
onActive(func) {
if (this.connected) func();
else this.activeConnectionEvent.push(func);
}
onPassive(func) {
if (!this.connected) func();
else this.passiveConnectionEvent.push(func);
}
eventMessage(data) {
if (typeof data == "string") {
let $data = JSON.parse(data);
for (const callback of this.recaivePackEvent)callback($data);
}
}
tranferToServer(data) {
if (this.connected) this.ws.send(JSON.stringify(data));
}
}
class $8792581153d3df4a$export$2e2bcd8739ae039 {
constructor(wsts){
this.events = new Map();
this.signals = new Map();
this.requests = new Map();
this.count = 0;
this.wsts = wsts;
}
request(msg) {
return new Promise((ok, rej)=>{
let id = ++this.count;
this.events.set(id, [
(data)=>{
ok(data);
},
(data)=>{
rej(data);
}
]);
this.wsts.WSTSProtocol.SendRequest(msg, id);
});
}
stream(msg, callback) {
let id = ++this.count;
this.wsts.WSTSProtocol.StartStream(msg, id);
this.events.set(id, [
(data)=>{
callback(data);
},
()=>{}
]);
}
signal(event, callback) {
let T = this.signals.get(event);
if (!T) this.signals.set(event, [
callback
]);
else T.push(callback);
}
}
class $90404382037abbde$export$2e2bcd8739ae039 {
emit(eventName, ...args) {
if (this.events[eventName]) for (const callback of this.events[eventName])callback(...args);
}
on(eventName, callback) {
if (this.events[eventName]) this.events[eventName].push(callback);
else this.events[eventName] = [
callback
];
}
scope(f) {
if (this.activeScope) f();
else this.on('scope', f);
}
constructor(){
this.events = {};
this.activeScope = false;
}
}
class $bce1fa8513c32a76$export$cd59d3e68ede65a1 {
constructor(mwse){
this.mwse = mwse;
}
async allocAPIPAddress() {
let { status: status, ip: ip } = await this.mwse.EventPooling.request({
type: 'alloc/APIPAddress'
});
if (status == 'success') {
this.APIPAddress = ip;
return ip;
} else throw new Error("Error Allocated Access Point IP Address");
}
async allocAPNumber() {
let { status: status, number: number } = await this.mwse.EventPooling.request({
type: 'alloc/APNumber'
});
if (status == 'success') {
this.APNumber = number;
return number;
} else throw new Error("Error Allocated Access Point Number");
}
async allocAPShortCode() {
let { status: status, code: code } = await this.mwse.EventPooling.request({
type: 'alloc/APShortCode'
});
if (status == 'success') {
this.APShortCode = code;
return code;
} else throw new Error("Error Allocated Access Point Short Code");
}
async reallocAPIPAddress() {
let { status: status, ip: ip } = await this.mwse.EventPooling.request({
type: 'realloc/APIPAddress'
});
if (status == 'success') {
this.APIPAddress = ip;
return ip;
} else throw new Error("Error Reallocated Access Point IP Address");
}
async reallocAPNumber() {
let { status: status, number: number } = await this.mwse.EventPooling.request({
type: 'realloc/APNumber'
});
if (status == 'success') {
this.APNumber = number;
return number;
} else throw new Error("Error Reallocated Access Point Number");
}
async reallocAPShortCode() {
let { status: status, code: code } = await this.mwse.EventPooling.request({
type: 'realloc/APShortCode'
});
if (status == 'success') {
this.APShortCode = code;
return code;
} else throw new Error("Error Reallocated Access Point Short Code");
}
async releaseAPIPAddress() {
let { status: status } = await this.mwse.EventPooling.request({
type: 'release/APIPAddress'
});
if (status == 'success') this.APIPAddress = undefined;
else throw new Error("Error release Access Point IP Address");
}
async releaseAPNumber() {
let { status: status } = await this.mwse.EventPooling.request({
type: 'release/APNumber'
});
if (status == 'success') this.APNumber = undefined;
else throw new Error("Error release Access Point Number");
}
async releaseAPShortCode() {
let { status: status } = await this.mwse.EventPooling.request({
type: 'release/APShortCode'
});
if (status == 'success') this.APShortCode = undefined;
else throw new Error("Error release Access Point Short Code");
}
async queryAPIPAddress(ip) {
let { status: status, socket: socket } = await this.mwse.EventPooling.request({
type: 'whois/APIPAddress',
whois: ip
});
if (status == "success") return socket;
else return null;
}
async queryAPNumber(number) {
let { status: status, socket: socket } = await this.mwse.EventPooling.request({
type: 'whois/APNumber',
whois: number
});
if (status == "success") return socket;
else return null;
}
async queryAPShortCode(code) {
let { status: status, socket: socket } = await this.mwse.EventPooling.request({
type: 'whois/APShortCode',
whois: code
});
if (status == "success") return socket;
else return null;
}
}
class $008a5dfecd0a1d37$export$f3bd5f68ae16de {
constructor(mwse){
this.info = {};
this.peer = mwse;
}
async fetch(name) {
if (name) {
let rinfo = await this.peer.mwse.EventPooling.request({
type: "peer/info",
peer: this.peer.socketId,
name: name
});
if (rinfo.status == "success") this.info = rinfo.info;
else console.warn(rinfo.message);
} else {
let rinfo = await this.peer.mwse.EventPooling.request({
type: "peer/info",
peer: this.peer.socketId
});
if (rinfo.status == "success") this.info = rinfo.info;
else console.warn(rinfo.message);
}
return this.info;
}
set(name, value) {
this.info[name] = value;
this.peer.mwse.WSTSProtocol.SendOnly({
type: "auth/info",
name: name,
value: value
});
}
get(name) {
return name ? this.info[name] : this.info;
}
}
class $e751e9f3ea17ef94$export$2e2bcd8739ae039 {
constructor(webrtc, peer){
this.totalSize = 0;
this.isReady = false;
this.isStarted = false;
this.isSending = false;
this.isRecaiving = false;
this.processedSize = 0;
this.bufferSizePerChannel = 10e6;
this.bufferSizePerPack = 10e3;
this.safeBufferSizePerPack = 9999;
this.webrtc = webrtc;
this.rtc = webrtc.rtc;
this.peer = peer;
}
async RecaiveFile(_rtc, fileMetadata, channelCount, _totalSize, onEnded) {
//let totals = {};
// let index = 0;
/*setChannelStatus(Array.from({length:channelCount}).map((e, index) => {
return {
name: `${index+1}. Kanal`,
current: 0,
currentTotal: 0,
total: 0
}
}));*/ let parts = [];
this.webrtc.on('datachannel', (datachannel)=>{
//let channelIndex = index++;
let current = 0;
let totalSize = 0;
let currentPart = 0;
let bufferAmount = [];
datachannel.onmessage = function({ data: data }) {
if (totalSize == 0) {
let { size: size, part: part } = JSON.parse(data);
totalSize = size;
currentPart = part;
/*updateChannelStatus(channelIndex, n => {
return {
...n,
total: totalSize,
current: 0
}
});*/ datachannel.send("READY");
} else {
current += data.byteLength;
bufferAmount.push(data);
/*updateChannelStatus(channelIndex, n => {
return {
...n,
current: data.byteLength + n.current,
currentTotal: data.byteLength + n.currentTotal,
}
});
setProcessedSize(n => n + data.byteLength);*/ if (current == totalSize) {
parts[currentPart] = new Blob(bufferAmount);
bufferAmount = [];
//totals[datachannel.label] += totalSize;
totalSize = 0;
currentPart = 0;
current = 0;
datachannel.send("TOTAL_RECAIVED");
}
}
};
datachannel.onclose = ()=>{
channelCount--;
if (channelCount == 0) {
let file = new File(parts, fileMetadata.name, {
type: fileMetadata.type,
lastModified: +new Date
});
onEnded(file);
}
};
});
}
async SendFile(file, metadata) {
this.isSending = true;
this.isStarted = true;
let buffer = await file.arrayBuffer();
let partCount = Math.ceil(buffer.byteLength / 10e6);
let channelCount = Math.min(5, partCount);
if (this.webrtc.iceStatus != "connected") throw new Error("WebRTC is a not ready");
this.peer.send({
type: 'file',
name: file.name,
size: file.size,
mimetype: file.type,
partCount: partCount,
channelCount: channelCount,
metadata: metadata
});
let channels = [];
for(let channelIndex = 0; channelIndex < channelCount; channelIndex++){
let channel = this.rtc.createDataChannel("\\?\\file_" + channelIndex);
channel.binaryType = "arraybuffer";
await new Promise((ok)=>{
channel.onopen = ()=>{
ok(void 0);
};
});
channels.push(channel);
}
let currentPart = 0;
let next = ()=>{
if (currentPart < partCount) {
let bufferPart = buffer.slice(currentPart * 10e6, currentPart * 10e6 + 10e6);
currentPart++;
return [
bufferPart,
currentPart - 1
];
}
return [
false,
0
];
};
let spyChannelIndex = channels.length;
await new Promise((ok)=>{
for(let channelIndex = 0; channelIndex < channels.length; channelIndex++)this.sendPartition(channels[channelIndex], next, channelIndex, ()=>{
spyChannelIndex--;
if (spyChannelIndex == 0) {
this.isSending = false;
this.isStarted = false;
ok(undefined);
}
});
});
}
sendPartition(channel, nextblob10mb, _channelIndex, onEnded) {
let [currentBuffer, currentPartition] = nextblob10mb();
let currentPart = 0;
let next = ()=>{
if (!(currentBuffer instanceof ArrayBuffer)) return;
let bufferPart = currentBuffer.slice(currentPart * 16e3, currentPart * 16e3 + 16e3);
currentPart++;
if (bufferPart.byteLength != 0) /*
updateChannelStatus(channelIndex, n => {
return {
...n,
current: bufferPart.byteLength + n.current,
currentTotal: bufferPart.byteLength + n.currentTotal
}
});
setProcessedSize(n => n + bufferPart.byteLength);
*/ return bufferPart;
};
channel.addEventListener("message", ({ data: data })=>{
if (data == "READY") this.sendFileChannel(channel, next);
if (data == "TOTAL_RECAIVED") {
[currentBuffer, currentPartition] = nextblob10mb();
currentPart = 0;
if (currentBuffer != false) /*updateChannelStatus(channelIndex, n => {
return {
...n,
total: currentBuffer.byteLength,
current: 0,
}
});*/ channel.send(JSON.stringify({
size: currentBuffer.byteLength,
part: currentPartition
}));
else {
channel.close();
onEnded();
}
}
});
channel.send(JSON.stringify({
size: currentBuffer.byteLength,
part: currentPartition
}));
}
sendFileChannel(channel, getNextBlob) {
channel.addEventListener("bufferedamountlow", function() {
let buffer = getNextBlob();
if (buffer) channel.send(buffer);
});
channel.bufferedAmountLowThreshold = 15999;
let c = getNextBlob();
c && channel.send(c);
}
}
class $b8ba020b52f6b742$export$2e2bcd8739ae039 {
static{
this.channels = new Map();
}
static{
this.requireGC = false;
}
static{
this.defaultRTCConfig = {
iceCandidatePoolSize: 0,
iceTransportPolicy: "all",
rtcpMuxPolicy: "require"
};
}
isPolite() {
let myId = this.peer?.mwse.peer('me').socketId;
let peerId = this.peer?.socketId;
return myId < peerId;
}
static{
this.defaultICEServers = [
{
urls: "stun:stun.l.google.com:19302"
},
{
urls: "stun:stun1.l.google.com:19302"
},
{
urls: "stun:stun2.l.google.com:19302"
},
{
urls: "stun:stun3.l.google.com:19302"
},
{
urls: "stun:stun4.l.google.com:19302"
}
];
}
constructor(rtcConfig, rtcServers){
this.active = false;
this.connectionStatus = "new";
this.iceStatus = "new";
this.gatheringStatus = "new";
this.signalingStatus = "";
this.recaivingStream = new Map();
this.sendingStream = new Map();
this.events = {};
this.makingOffer = false;
this.ignoreOffer = false;
this.isSettingRemoteAnswerPending = false;
this.candicatePack = [];
let config = {};
if (rtcConfig) Object.assign(config, $b8ba020b52f6b742$export$2e2bcd8739ae039.defaultRTCConfig, rtcConfig);
else Object.assign(config, $b8ba020b52f6b742$export$2e2bcd8739ae039.defaultRTCConfig);
config.iceServers = rtcServers || $b8ba020b52f6b742$export$2e2bcd8739ae039.defaultICEServers;
this.rtc = new RTCPeerConnection(config);
this.rtc.addEventListener("connectionstatechange", ()=>{
this.eventConnectionState();
});
this.rtc.addEventListener("icecandidate", (...args)=>{
this.eventIcecandidate(...args);
});
this.rtc.addEventListener("iceconnectionstatechange", ()=>{
this.eventICEConnectionState();
});
this.rtc.addEventListener("icegatheringstatechange", ()=>{
this.eventICEGatherinState();
});
this.rtc.addEventListener("negotiationneeded", ()=>{
this.eventNogationNeeded();
});
this.rtc.addEventListener("signalingstatechange", ()=>{
this.eventSignalingState();
});
this.rtc.addEventListener("track", (...args)=>{
this.eventTrack(...args);
});
this.rtc.addEventListener("datachannel", (...args)=>{
this.eventDatachannel(...args);
});
this.on('input', async (data)=>{
switch(data.type){
case "icecandidate":
try {
if (this.rtc.remoteDescription) await this.rtc.addIceCandidate(new RTCIceCandidate(data.value));
else this.candicatePack.push(new RTCIceCandidate(data.value));
} catch (error) {
debugger;
} finally{
console.log("ICE Canbet");
}
break;
case "offer":
{
let readyForOffer = !this.makingOffer && (this.rtc.signalingState == "stable" || this.isSettingRemoteAnswerPending);
const offerCollision = !readyForOffer;
this.ignoreOffer = !this.isPolite() && offerCollision;
if (this.ignoreOffer) return;
this.isSettingRemoteAnswerPending = false;
await this.rtc.setRemoteDescription(new RTCSessionDescription(data.value));
this.isSettingRemoteAnswerPending = false;
for (const candidate of this.candicatePack)await this.rtc.addIceCandidate(candidate);
let answer = await this.rtc.createAnswer({
offerToReceiveAudio: true,
offerToReceiveVideo: true
});
await this.rtc.setLocalDescription(answer);
this.send({
type: 'answer',
value: answer
});
break;
}
case "answer":
await this.rtc.setRemoteDescription(new RTCSessionDescription(data.value));
for (const candidate of this.candicatePack)await this.rtc.addIceCandidate(candidate);
break;
case "streamInfo":
{
let { id: id, value: value } = data;
let streamInfo = this.recaivingStream.get(id);
if (!streamInfo) this.recaivingStream.set(id, value);
else this.recaivingStream.set(id, {
...streamInfo,
...value
});
this.send({
type: 'streamAccept',
id: id
});
break;
}
case "streamRemoved":
{
let { id: id } = data;
this.emit('stream:stopped', this.recaivingStream.get(id));
this.recaivingStream.delete(id);
break;
}
case "streamAccept":
{
let { id: id } = data;
let sendingStream = this.sendingStream.get(id);
let senders = [];
if (sendingStream && sendingStream.stream) {
for (const track of sendingStream.stream.getTracks())senders.push(this.rtc.addTrack(track, sendingStream.stream));
sendingStream.senders = senders;
}
break;
}
case "message":
this.emit('message', data.payload);
break;
}
});
}
addEventListener(event, callback) {
(this.events[event] || (this.events[event] = [])).push(callback);
}
on(event, callback) {
this.addEventListener(event, callback);
}
async dispatch(event, ...args) {
if (this.events[event]) for (const callback of this.events[event])await callback(...args);
}
async emit(event, ...args) {
await this.dispatch(event, ...args);
}
connect() {
if (!this.channel) this.createDefaultDataChannel();
}
sendMessage(data) {
this.send({
type: 'message',
payload: data
});
}
createDefaultDataChannel() {
let dt = this.rtc.createDataChannel(':default:', {
ordered: true
});
dt.addEventListener("open", ()=>{
this.channel = dt;
$b8ba020b52f6b742$export$2e2bcd8739ae039.channels.set(this.id, this);
this.active = true;
});
dt.addEventListener("message", ({ data: data })=>{
let pack = JSON.parse(data);
this.emit('input', pack);
});
dt.addEventListener("close", ()=>{
this.channel = undefined;
this.active = false;
});
}
destroy() {
this.active = false;
if (this.channel) {
this.channel.close();
this.channel = undefined;
}
if (this.rtc) this.rtc.close();
this.emit('disconnected');
$b8ba020b52f6b742$export$2e2bcd8739ae039.channels.delete(this.id);
}
eventDatachannel(event) {
if (event.channel.label == ':default:') {
$b8ba020b52f6b742$export$2e2bcd8739ae039.channels.set(this.id, this);
this.channel = event.channel;
this.active = true;
event.channel.addEventListener("message", ({ data: data })=>{
let pack = JSON.parse(data);
this.emit('input', pack);
});
event.channel.addEventListener("close", ()=>{
this.channel = undefined;
$b8ba020b52f6b742$export$2e2bcd8739ae039.channels.delete(this.id);
$b8ba020b52f6b742$export$2e2bcd8739ae039.requireGC = true;
});
} else this.emit('datachannel', event.channel);
}
send(data) {
if (this.channel?.readyState == "open") this.channel.send(JSON.stringify(data));
else this.emit('output', data);
}
eventConnectionState() {
this.connectionStatus = this.rtc.connectionState;
if (this.connectionStatus == 'connected') {
if (this.active == false) this.emit('connected');
}
if (this.connectionStatus == 'failed') this.rtc.restartIce();
if (this.connectionStatus == "closed") {
if (this.active) this.destroy();
}
}
eventIcecandidate(event) {
if (event.candidate) this.send({
type: 'icecandidate',
value: event.candidate
});
}
eventICEConnectionState() {
this.iceStatus = this.rtc.iceConnectionState;
}
eventICEGatherinState() {
this.gatheringStatus = this.rtc.iceGatheringState;
}
async eventNogationNeeded() {
try {
this.makingOffer = true;
let offer = await this.rtc.createOffer({
iceRestart: true,
offerToReceiveAudio: true,
offerToReceiveVideo: true
});
await this.rtc.setLocalDescription(offer);
this.send({
type: 'offer',
value: offer
});
} catch (error) {
console.error(`Nogation Error:`, error);
} finally{
this.makingOffer = false;
}
}
eventSignalingState() {
this.signalingStatus = this.rtc.signalingState;
}
eventTrack(event) {
let rtpRecaiver = event.receiver;
if (event.streams.length) for (const stream of event.streams){
let streamInfo = this.recaivingStream.get(stream.id);
(streamInfo.recaivers || (streamInfo.recaivers = [])).push(rtpRecaiver);
if (this.recaivingStream.get(stream.id).stream == null) {
streamInfo.stream = stream;
this.emit('stream:added', this.recaivingStream.get(stream.id));
} else streamInfo.stream = stream;
}
}
sendStream(stream, name, info) {
this.send({
type: 'streamInfo',
id: stream.id,
value: {
...info,
name: name
}
});
this.sendingStream.set(stream.id, {
...info,
id: stream.id,
name: name,
stream: stream
});
}
stopStream(_stream) {
if (this.connectionStatus != 'connected') return;
if (this.sendingStream.has(_stream.id)) {
let { stream: stream } = this.sendingStream.get(_stream.id);
for (const track of stream.getTracks()){
for (const RTCPSender of this.rtc.getSenders())if (RTCPSender.track?.id == track.id) this.rtc.removeTrack(RTCPSender);
}
this.send({
type: 'streamRemoved',
id: stream.id
});
this.sendingStream.delete(_stream.id);
}
}
stopAllStreams() {
if (this.connectionStatus != 'connected') return;
for (const [, { stream: stream }] of this.sendingStream){
if (stream == undefined) continue;
for (const track of stream.getTracks()){
for (const RTCPSender of this.rtc.getSenders())if (RTCPSender.track?.id == track.id) this.rtc.removeTrack(RTCPSender);
}
this.send({
type: 'streamRemoved',
id: stream.id
});
}
this.sendingStream.clear();
}
async SendFile(file, meta) {
if (!this.peer) throw new Error("Peer is not ready");
this.FileTransportChannel = new (0, $e751e9f3ea17ef94$export$2e2bcd8739ae039)(this, this.peer);
await this.FileTransportChannel.SendFile(file, meta);
}
async RecaiveFile(chnlCount, filemeta, totalSize) {
if (!this.peer) throw new Error("Peer is not ready");
this.FileTransportChannel = new (0, $e751e9f3ea17ef94$export$2e2bcd8739ae039)(this, this.peer);
return await new Promise((recaivedFile)=>{
if (this.FileTransportChannel) this.FileTransportChannel.RecaiveFile(this.rtc, filemeta, chnlCount, totalSize, (file)=>{
recaivedFile(file);
});
});
}
}
$b8ba020b52f6b742$export$2e2bcd8739ae039.requireGC = false;
setInterval(()=>{
if ($b8ba020b52f6b742$export$2e2bcd8739ae039.requireGC == false) return;
let img = document.createElement("img");
img.src = window.URL.createObjectURL(new Blob([
new ArrayBuffer(5e+7)
]));
img.onerror = function() {
window.URL.revokeObjectURL(this.src);
};
$b8ba020b52f6b742$export$2e2bcd8739ae039.requireGC = false;
}, 3000);
var $869de8be2afc3a3b$var$IMessageSymbase = /*#__PURE__*/ function(IMessageSymbase) {
IMessageSymbase[IMessageSymbase["PayloadMessagePack"] = -12873.54] = "PayloadMessagePack";
IMessageSymbase[IMessageSymbase["PayloadRTCBasePack"] = -12884.54] = "PayloadRTCBasePack";
return IMessageSymbase;
}($869de8be2afc3a3b$var$IMessageSymbase || {});
class $869de8be2afc3a3b$export$2e2bcd8739ae039 extends (0, $90404382037abbde$export$2e2bcd8739ae039) {
constructor(wsts){
super(), this.options = {}, this.selfSocket = false, this.active = false, this.peerConnection = false, this.primaryChannel = "datachannel";
this.mwse = wsts;
this.rtc = this.createRTC();
this.info = new (0, $008a5dfecd0a1d37$export$f3bd5f68ae16de)(this);
this.on('pack', (data)=>{
if (data.type == ':rtcpack:') return this.rtc.emit("input", data.payload);
this.emit("message", data);
});
}
createRTC(rtcConfig, rtcServers) {
this.rtc = new (0, $b8ba020b52f6b742$export$2e2bcd8739ae039)(rtcConfig, rtcServers);
this.rtc.peer = this;
this.rtc.on("connected", ()=>{
this.peerConnection = true;
});
this.rtc.on('disconnected', ()=>{
this.peerConnection = false;
});
this.rtc.on("output", (payload)=>{
this.send({
type: ':rtcpack:',
payload: payload
});
});
this.rtc.on("message", (payload)=>{
this.emit("pack", payload);
});
return this.rtc;
}
setPeerOptions(options) {
if (typeof options == "string") this.setSocketId(options);
else this.options = options;
}
setSocketId(uuid) {
this.socketId = uuid;
}
async metadata() {
if (this.socketId == 'me') {
let result = await this.mwse.EventPooling.request({
type: 'my/socketid'
});
this.selfSocket = true;
this.active ||= true;
this.socketId = result;
this.emit('scope');
this.activeScope = true;
return result;
}
}
async request(pack) {
if (this.active) return await this.mwse.request(this.socketId, pack);
}
equalTo(peer) {
return this.socketId == peer.socketId;
}
async isReachable() {
return await this.mwse.EventPooling.request({
type: 'is/reachable',
to: this.socketId
});
}
async enablePairAuth() {
await this.mwse.EventPooling.request({
type: 'auth/pair-system',
value: 'everybody'
});
}
async disablePairAuth() {
await this.mwse.EventPooling.request({
type: 'auth/pair-system',
value: 'disable'
});
}
async enablePairInfo() {
await this.mwse.EventPooling.request({
type: 'connection/pairinfo',
value: true
});
}
async disablePairInfo() {
await this.mwse.EventPooling.request({
type: 'connection/pairinfo',
value: false
});
}
async requestPair() {
let { message: message, status: status } = await this.mwse.EventPooling.request({
type: 'request/pair',
to: this.socketId
});
if (message == "ALREADY-PAIRED" || message == "ALREADY-REQUESTED") console.warn("Already paired or pair requested");
if (status == "fail") {
console.error("Request Pair Error", status, message);
return false;
}
return true;
}
async endPair() {
await this.mwse.EventPooling.request({
type: 'end/pair',
to: this.socketId
});
this.forget();
}
async acceptPair() {
let { message: message, status: status } = await this.mwse.EventPooling.request({
type: 'accept/pair',
to: this.socketId
});
if (status == "fail") {
console.error("Pair Error", status, message);
return false;
}
return true;
}
async rejectPair() {
let { message: message, status: status } = await this.mwse.EventPooling.request({
type: 'reject/pair',
to: this.socketId
});
if (status == "fail") {
console.error("Pair Error", status, message);
return false;
}
return true;
}
async getPairedList() {
let { value: value } = await this.mwse.EventPooling.request({
type: 'pair/list',
to: this.socketId
});
return value;
}
async send(pack) {
let isOpenedP2P = this.peerConnection && this.rtc?.active;
let isOpenedServer = this.mwse.server.connected;
let sendChannel;
if (isOpenedP2P && isOpenedServer) {
if (this.primaryChannel == "websocket") sendChannel = "websocket";
else sendChannel = "datachannel";
} else if (isOpenedServer) sendChannel = "websocket";
else sendChannel = "datachannel";
if (sendChannel == "websocket") {
if (!this.mwse.writable) return console.warn("Socket is not writable");
await this.mwse.EventPooling.request({
type: 'pack/to',
pack: pack,
to: this.socketId
});
} else this.rtc?.sendMessage(pack);
}
async forget() {
this.mwse.peers.delete(this.socketId);
this.mwse.pairs.delete(this.socketId);
}
}
class $de3b1e8f1edf2641$export$f106f681f3286480 {
constructor(room){
this.info = {};
this.room = room;
this.room.on('updateinfo', (name, value)=>{
this.info[name] = value;
});
}
async fetch(name) {
if (name) {
let rinfo = await this.room.mwse.EventPooling.request({
type: "room/getinfo",
roomId: this.room.roomId,
name: name
});
if (rinfo.status == "success") this.info = rinfo.value;
else console.warn(rinfo.message);
} else {
let rinfo = await this.room.mwse.EventPooling.request({
type: "room/info",
roomId: this.room.roomId
});
if (rinfo.status == "success") this.info = rinfo.value;
else console.warn(rinfo.message);
}
return this.info;
}
set(name, value) {
this.info[name] = value;
this.room.mwse.WSTSProtocol.SendOnly({
type: "room/setinfo",
roomId: this.room.roomId,
name: name,
value: value
});
}
get(name) {
return name ? this.info[name] : this.info;
}
}
class $50cc11879cbf9e58$export$2e2bcd8739ae039 extends (0, $90404382037abbde$export$2e2bcd8739ae039) {
constructor(wsts){
super(), this.peers = new Map();
this.mwse = wsts;
this.info = new (0, $de3b1e8f1edf2641$export$f106f681f3286480)(this);
}
setRoomOptions(options) {
if (typeof options == "string") this.roomId = options;
else {
let defaultOptions = {
joinType: "free",
ifexistsJoin: true,
accessType: "private",
notifyActionInvite: true,
notifyActionJoined: true,
notifyActionEjected: true,
autoFetchInfo: true
};
Object.assign(defaultOptions, options);
this.config = defaultOptions;
}
}
setRoomId(uuid) {
this.roomId = uuid;
}
async createRoom(roomOptions) {
let config = this.config || roomOptions;
let result = await this.mwse.EventPooling.request({
type: 'create-room',
...config
});
if (result.status == 'fail') {
if (result.message == "ALREADY-EXISTS" && this.config.ifexistsJoin) return this.join();
throw new Error(result.message || result.messages);
} else {
this.options = {
...this.config,
...result.room
};
this.roomId = result.room.id;
this.mwse.rooms.set(this.roomId, this);
}
}
async join() {
let result = await this.mwse.EventPooling.request({
type: 'joinroom',
name: this.config.name,
credential: this.config.credential,
autoFetchInfo: this.config.autoFetchInfo || false
});
if (result.status == 'fail') throw new Error(result.message);
else {
this.options = {
...this.config,
...result.room
};
if (result.info) this.info.info = result.info;
this.roomId = result.room.id;
this.mwse.rooms.set(this.roomId, this);
}
}
async eject() {
let { type: type } = await this.mwse.EventPooling.request({
type: 'ejectroom',
roomId: this.roomId
});
this.peers.clear();
if (type == 'success') this.mwse.rooms.delete(this.roomId);
}
async send(pack, wom = false, handshake = false) {
if (!this.mwse.writable) return console.warn("Socket is not writable");
if (handshake) {
let { type: type } = await this.mwse.EventPooling.request({
type: 'pack/room',
pack: pack,
to: this.roomId,
wom: wom,
handshake: handshake
});
if (type == "fail") throw new Error("Cant send message to room");
} else await this.mwse.EventPooling.request({
type: 'pack/room',
pack: pack,
to: this.roomId,
wom: wom,
handshake: handshake
});
}
async fetchPeers(filter, onlyNumber = false) {
if (onlyNumber) {
let { count: count } = await this.mwse.EventPooling.request({
type: 'room/peer-count',
roomId: this.roomId,
filter: filter || {}
});
return count;
} else {
let { status: status, peers: peers } = await this.mwse.EventPooling.request({
type: 'room-peers',
roomId: this.roomId,
filter: filter || {}
});
let cup = [];
if (status == 'fail') throw new Error("Cant using peers on room");
else if (status == 'success') for (const peerid of peers){
let peer = this.mwse.peer(peerid, true);
cup.push(peer);
this.peers.set(peerid, peer);
}
return cup;
}
}
}
class $ce70fc8599fd5132$export$2e2bcd8739ae039 {
constructor(wsts){
this.mwse = wsts;
this.addListener();
}
addListener() {
this.mwse.server?.onRecaivePack((pack)=>{
this.PackAnalyze(pack);
});
}
SendRaw(pack) {
this.mwse.server.tranferToServer(pack);
}
SendOnly(pack) {
this.mwse.server.tranferToServer([
pack,
'R'
]);
}
SendRequest(pack, id) {
this.mwse.server.tranferToServer([
pack,
id,
'R'
]);
}
StartStream(pack, id) {
this.mwse.server.tranferToServer([
pack,
id,
'S'
]);
}
PackAnalyze(data) {
let [payload, id, action] = data;
if (typeof id === 'number') {
let callback = this.mwse.EventPooling.events.get(id);
if (callback) {
callback[0](payload, action);
switch(action){
case 'E':
this.mwse.EventPooling.events.delete(id);
break;
case 'S':
default:
break;
}
} else console.warn("Missing event sended from server");
} else {
let signals = this.mwse.EventPooling.signals.get(id);
if (signals) for (const callback of signals)callback(payload);
else console.warn("Missing event sended from server");
}
}
}
class $965027aeec3df663$export$2e2bcd8739ae039 extends (0, $90404382037abbde$export$2e2bcd8739ae039) {
/*public static compress(message:string, callback:(e:any) => any)
{
let u : any= [];
let C = new Gzip({
level: 9,
mem: 12
},(stream,isLast) => {
u.push(stream);
if(isLast)
{
callback(u);
}
});
C.push(new TextEncoder().encode(message), true);
}*/ constructor(options){
super(), this.rooms = new Map(), this.pairs = new Map(), this.peers = new Map(), this.writable = 1, this.readable = 1;
$965027aeec3df663$export$2e2bcd8739ae039.rtc = $965027aeec3df663$export$2e2bcd8739ae039;
this.server = new (0, $d59cdc9b12df098b$export$98b66c25bb38499d)(this, options);
this.WSTSProtocol = new (0, $ce70fc8599fd5132$export$2e2bcd8739ae039)(this);
this.EventPooling = new (0, $8792581153d3df4a$export$2e2bcd8739ae039)(this);
this.virtualPressure = new (0, $bce1fa8513c32a76$export$cd59d3e68ede65a1)(this);
this.server.connect();
this.me = new (0, $869de8be2afc3a3b$export$2e2bcd8739ae039)(this);
this.me.scope(()=>{
this.peers.set('me', this.me);
this.peers.set(this.me.socketId, this.me);
});
this.server.onActive(async ()=>{
this.me.setSocketId('me');
await this.me.metadata();
this.emit('scope');
this.activeScope = true;
});
this.server.onPassive(async ()=>{
this.emit('close');
});
this.packMessagingSystem();
}
destroy() {
this.server.disconnect();
}
enableRecaiveData() {
this.WSTSProtocol.SendOnly({
type: 'connection/packrecaive',
value: 1
});
this.readable = 1;
}
disableRecaiveData() {
this.WSTSProtocol.SendOnly({
type: 'connection/packrecaive',
value: 0
});
this.readable = 0;
}
enableSendData() {
this.WSTSProtocol.SendOnly({
type: 'connection/packsending',
value: 1
});
this.writable = 1;
}
disableSendData() {
this.WSTSProtocol.SendOnly({
type: 'connection/packsending',
value: 0
});
this.writable = 0;
}
enableNotifyRoomInfo() {
this.WSTSProtocol.SendOnly({
type: 'connection/roominfo',
value: 1
});
}
disableNotifyRoomInfo() {
this.WSTSProtocol.SendOnly({
type: 'connection/roominfo',
value: 0
});
}
async request(peerId, pack) {
let { pack: answer } = await this.EventPooling.request({
type: 'request/to',
to: peerId,
pack: pack
});
return answer;
}
async response(peerId, requestId, pack) {
this.WSTSProtocol.SendOnly({
type: 'response/to',
to: peerId,
pack: pack,
id: requestId
});
}
packMessagingSystem() {
this.EventPooling.signal('pack', (payload)=>{
if (this.readable) {
let { from: from, pack: pack } = payload;
this.peer(from, true).emit('pack', pack);
}
});
this.EventPooling.signal('request', (payload)=>{
let { from: from, pack: pack, id: id } = payload;
let scope = {
body: pack,
response: (pack)=>{
this.response(from, id, pack);
},
peer: this.peer(from, true)
};
this.peer(from, true).emit('request', scope);
this.peer('me').emit('request', scope);
});
this.EventPooling.signal('pack/room', (payload)=>{
if (this.readable) {
let { from: from, pack: pack, sender: sender } = payload;
this.room(from).emit('message', pack, this.peer(sender));
}
});
this.EventPooling.signal('room/joined', (payload)=>{
let { id: id, roomid: roomid } = payload;
let room = this.room(roomid);
let peer = this.peer(id, true);
room.peers.set(peer.socketId, peer);
room.emit('join', peer);
});
this.EventPooling.signal('room/info', (payload)=>{
let { roomId: roomId, name: name, value: value } = payload;
this.room(roomId).emit('updateinfo', name, value);
});
this.EventPooling.signal('room/ejected', (payload)=>{
let { id: id, roomid: roomid } = payload;
let room = this.room(roomid);
let peer = this.peer(id, true);
room.peers.delete(peer.socketId);
room.emit('eject', peer);
});
this.EventPooling.signal('room/closed', (payload)=>{
let { roomid: roomid } = payload;
let room = this.room(roomid);
room.peers.clear();
room.emit('close');
this.rooms.delete(roomid);
});
this.EventPooling.signal("pair/info", (payload)=>{
let { from: from, name: name, value: value } = payload;
let peer = this.peer(from, true);
peer.info.info[name] = value;
peer.emit("info", name, value);
});
this.EventPooling.signal("request/pair", (payload)=>{
let { from: from, info: info } = payload;
let peer = this.peer(from, true);
peer.info.info = info;
peer.emit("request/pair", peer);
this.peer('me').emit('request/pair', peer);
});
this.EventPooling.signal("peer/disconnect", (payload)=>{
let { id: id } = payload;
let peer = this.peer(id, true);
peer.emit("disconnect", peer);
});
this.EventPooling.signal("accepted/pair", (payload)=>{
let { from: from, info: info } = payload;
let peer = this.peer(from, true);
peer.info.info = info;
peer.emit("accepted/pair", peer);
this.peer('me').emit('accepted/pairr', peer);
});
this.EventPooling.signal("end/pair", (payload)=>{
let { from: from, info: info } = payload;
let peer = this.peer(from, true);
peer.emit("endPair", info);
this.peer('me').emit('endPair', from, info);
});
}
room(options) {
if (typeof options == "string") {
if (this.rooms.has(options)) return this.rooms.get(options);
}
let room = new (0, $50cc11879cbf9e58$export$2e2bcd8739ae039)(this);
room.setRoomOptions(options);
this.emit('room');
return room;
}
peer(options, isActive = false) {
if (typeof options == "string") {
if (this.peers.has(options)) return this.peers.get(options);
if (this.pairs.has(options)) return this.pairs.get(options);
}
let peer = new (0, $869de8be2afc3a3b$export$2e2bcd8739ae039)(this);
peer.setPeerOptions(options);
peer.active = isActive;
this.peers.set(peer.socketId, peer);
this.emit('peer', peer);
return peer;
}
}
window.MWSE = $965027aeec3df663$export$2e2bcd8739ae039;
})();
//# sourceMappingURL=index.js.map