Newer
Older
import LioWebRTC from "liowebrtc"
function extend(Y) {
class WebRTC extends Y.AbstractConnector {
constructor(y, options) {
if (options === undefined) {
throw new Error("Options must not be undefined!")
}
options.role = "slave"
super(y, options)
this.webrtcOptions = options
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
this.queue = new Worker("js/queue.js")
this.queue.onmessage = (event) => {
const method = event.data.method
if (method == "send") {
const { uid, channel, message } = event.data
// y-js db transactions can send messages after a peer has disconnected
if (
(channel == "y-js" && !this.peers.has(uid)) ||
!this.webrtc.getPeerById(uid)
) {
return
}
this.webrtc.whisper(this.webrtc.getPeerById(uid), channel, message)
} else if (method == "broadcast") {
const { channel, message } = event.data
return this.webrtc.shout(channel, message)
} else if (method == "received") {
const { type, message, peer } = event.data
if (type === "tw-ml") {
// Handshakes can only be sent and received directly
if (message === "tw") {
// Response message in the handshake
this.queue.postMessage({
method: "send",
uid: peer.id,
channel: "tw-ml",
message: "ml",
})
} else if (message == "ml") {
// Handshake completed
this.checkAndInsertPeer(peer.id)
}
} else {
this.checkAndInsertPeer(peer.id)
if (type === "y-js") {
this.checkAndInsertPeer(peer.id)
this.receiveMessage(peer.id, message)
}
}
}
}
if (options.onUserEvent) {
this.onUserEvent(options.onUserEvent)
}
this.initialiseConnection()
Momo Langenstein
committed
window.addEventListener("unload", () => {
this.y.destroy()
})
initialiseConnection() {
Momo Langenstein
committed
this.webrtc = new LioWebRTC({
url: this.webrtcOptions.url,
dataOnly: true,
Moritz Langenstein
committed
/*network: {
minPeers: 4,
maxPeers: 8,
Moritz Langenstein
committed
},*/
this.peers = new Map()
Momo Langenstein
committed
this.webrtc.on("ready", () => {
this.webrtc.joinRoom(this.webrtcOptions.room)
})
Moritz Langenstein
committed
Momo Langenstein
committed
this.webrtc.on("joinedRoom", () => {
this.checkAndEnsureUser()
console.log("TODO: LEFT ROOM")
this.webrtc.on("channelError", (a, b, c, d) => console.log(a, b, c, d))
Momo Langenstein
committed
this.webrtc.on("channelOpen", (dataChannel, peer) => {
this.checkAndEnsureUser()
// Start a handshake to ensure both sides are able to use the channel
function handshake(peer) {
const _peer = this.webrtc.getPeerById(peer.id)
if (!_peer || _peer !== peer) {
return
}
Momo Langenstein
committed
if (this.peers.has(peer.id)) {
return
}
// Initial message in the handshake
this.queue.postMessage({
method: "send",
uid: peer.id,
channel: "tw-ml",
message: "tw",
})
Momo Langenstein
committed
setTimeout(handshake.bind(this, peer), 500)
Momo Langenstein
committed
setTimeout(handshake.bind(this, peer), 100)
})
Momo Langenstein
committed
this.webrtc.on("receivedPeerData", (type, message, peer) => {
this.checkAndEnsureUser()
// Message could have been forwarded but yjs only needs to know about directly connected peers
this.queue.postMessage({
method: "received",
type,
message,
peer: { id: peer.forwardedBy ? peer.forwardedBy.id : peer.id },
})
})
Momo Langenstein
committed
this.webrtc.on("channelClose", (dataChannel, peer) => {
this.checkAndEnsureUser()
this.checkAndRemovePeer(peer.id)
})
Momo Langenstein
committed
// Ensure that y-js is up to date on the user's id
checkAndEnsureUser() {
const id = this.webrtc.getMyId()
if (this.y.db.userId === id) {
return
}
Momo Langenstein
committed
f({ action: "userID", id: id })
}
this.setUserId(id)
}
// Ensure that y-js knows that the peer has joined
checkAndInsertPeer(uid) {
if (this.peers.has(uid)) {
return
}
console.log(
this.webrtc
.getPeerById(uid)
.getStats(null)
.then((stats) => stats.forEach((report) => console.log(report))),
)
const health = {}
health.cb = setInterval(
this.heartbeat.bind(this, this.webrtc.getPeerById(uid), health),
500,
)
this.peers.set(uid, health)
Momo Langenstein
committed
this.userJoined(uid, "master")
}
heartbeat(peer, health) {
const _peer = this.webrtc.getPeerById(peer.id)
if (!_peer || _peer !== peer || !this.peers.has(peer.id)) {
clearInterval(health.cb)
return
}
const self = this
// TODO: Check which stats are supported by different browsers
// TODO: Check massive renegotiation on reconnect
peer.getStats(null).then((stats) => {
stats.forEach((report) => {
if (report.type == "candidate-pair" && report.selected) {
if (Date.now() - report.lastPacketReceivedTimestamp > 10000) {
return peer.end(true)
}
if (Date.now() - report.lastPacketReceivedTimestamp > 500) {
self.queue.postMessage({
method: "send",
uid: peer.id,
channel: "heartbeat",
})
}
}
})
})
}
Momo Langenstein
committed
// Ensure that y-js knows that the peer has left
checkAndRemovePeer(uid) {
if (!this.peers.has(uid)) {
return
}
this.peers.delete(uid)
this.userLeft(uid)
}
connectToPeer(/*uid*/) {
// currently deprecated
this.queue.terminate()
this.webrtc.quit()
super.disconnect()
}
reconnect() {
this.initialiseConnection()
send(uid, message) {
this.queue.postMessage({ method: "send", channel: "y-js", uid, message })
}
broadcast(message) {
this.queue.postMessage({ method: "broadcast", channel: "y-js", message })
isDisconnected() {
return false
}
}
Y.extend("webrtc", WebRTC)
}
if (typeof Y !== "undefined") {
extend(Y)
}