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
this.initialiseConnection()
initialiseConnection() {
const webrtc = new LioWebRTC({
url: this.webrtcOptions.url,
dataOnly: true,
Moritz Langenstein
committed
/*network: {
minPeers: 4,
maxPeers: 8,
Moritz Langenstein
committed
},*/
this.webrtc = webrtc
webrtc.on("ready", () => {
webrtc.joinRoom(this.webrtcOptions.room)
Moritz Langenstein
committed
webrtc.connection.on("message", (data) =>
console.log("socket.io", data),
)
})
webrtc.on("joinedRoom", () => {
const id = webrtc.getMyId()
for (let f of this.userEventListeners) {
f({ action: "userID", id: id })
}
this.setUserId(id)
})
// Cannot use createdPeer here as y-js will then try to send data before the channel is open
webrtc.on("channelOpen", (dataChannel, peer) => {
Moritz Langenstein
committed
console.log(
"createdPeer",
peer.id,
this.webrtc.getPeers().map((peer) => peer.id),
)
this.userJoined(peer.id, "master")
})
webrtc.on("receivedPeerData", (type, message, peer) => {
Moritz Langenstein
committed
if (message.type !== "update")
console.log(
"receivedData",
peer.id,
message,
this.webrtc.getPeers().map((peer) => peer.id),
)
this.receiveMessage(peer.id, message)
})
Moritz Langenstein
committed
webrtc.on("channelClose", (dataChannel, peer) => {
console.log(
"removedPeer",
peer.id,
this.webrtc.getPeers().map((peer) => peer.id),
)
this.userLeft(peer.id)
connectToPeer(/*uid*/) {
// currently deprecated
this.webrtc.quit()
super.disconnect()
}
reconnect() {
this.initialiseConnection()
send(uid, message) {
Moritz Langenstein
committed
console.log(
"send",
uid,
message,
this.webrtc.getPeers().map((peer) => peer.id),
)
this.webrtc.whisper(this.webrtc.getPeerById(uid), "y-js", message)
}
broadcast(message) {
Moritz Langenstein
committed
if (message.type !== "update")
console.log(
"broadcast",
message,
this.webrtc.getPeers().map((peer) => peer.id),
)
this.webrtc.shout("y-js", message)
isDisconnected() {
return false
}
}
Y.extend("webrtc", WebRTC)
}
if (typeof Y !== "undefined") {
extend(Y)
}