Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import AbstractConnection from "./Connection.js"
import LioWebRTC from "liowebrtc"
export default class WebRTCConnection extends AbstractConnection {
constructor(options) {
super(options)
this.webrtc = new LioWebRTC({
url: this.options.url,
dataOnly: true,
constraints: {
minPeers: this.options.mesh.minPeers,
maxPeers: this.options.mesh.maxPeers,
},
})
this.webrtc.on("ready", () => {
this.webrtc.joinRoom(this.options.room)
})
this.webrtc.on("joinedRoom", () => {
this.dispatchEvent(new CustomEvent("roomJoined"))
})
this.webrtc.on("leftRoom", () => {
this.dispatchEvent(new CustomEvent("roomLeft"))
})
this.webrtc.on("channelOpen", (dataChannel, peer) => {
this.dispatchEvent(new CustomEvent("channelOpened", { detail: peer.id }))
})
this.webrtc.on("channelError", (dataChannel, peer) => {
this.dispatchEvent(new CustomEvent("channelError", { detail: peer.id }))
})
this.webrtc.on("channelClose", (dataChannel, peer) => {
this.dispatchEvent(new CustomEvent("channelClosed", { detail: peer.id }))
})
this.webrtc.on("receivedPeerData", (channel, message, peer) => {
// Message could have been forwarded but interface only needs to know about directly connected peers
this.dispatchEvent(
new CustomEvent("messageReceived", {
detail: {
uid: peer.forwardedBy ? peer.forwardedBy.id : peer.id,
channel,
message,
},
}),
)
})
}
getUserID() {
return this.webrtc.getMyId()
}
getPeerHandle(uid) {
return this.webrtc.getPeerById(uid)
}
getPeerFootprint(uid) {
const peer = this.webrtc.getPeerById(uid)
if (!peer) return Promise.reject()
return new Promise(function(resolve, reject) {
peer.getStats(null).then((stats) => {
let footprint = -1
stats.forEach((report) => {
if (
report.type == "candidate-pair" &&
report.bytesSent > 0 &&
report.bytesReceived > 0 &&
report.writable
) {
footprint = Math.max(footprint, report.bytesReceived)
}
})
if (footprint != -1) {
resolve(footprint)
} else {
reject()
}
})
})
}
send(uid, channel, message) {
const peer = this.webrtc.getPeerById(uid)
if (!peer) return
this.webrtc.whisper(peer, channel, message)
}
broadcast(channel, message) {
this.webrtc.shout(channel, message)
}
terminatePeer(uid) {
const peer = this.webrtc.getPeerById(uid)
if (!peer) return
peer.end()
}
destructor() {
this.webrtc.quit()
}
}