Newer
Older
/* global Y */
"use strict"
var {
Moritz Langenstein
committed
peerjs: { Peer },
} = require("peerjs")
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() {
var peer = new Peer({
host: this.webrtcOptions.host,
port: this.webrtcOptions.port,
Moritz Langenstein
committed
path: this.webrtcOptions.path,
this.peer = peer
var self = this
this.peers = new Map()
Moritz Langenstein
committed
//console.log("My peer ID is: " + id)
for (var f of self.userEventListeners) {
f({ action: "userID", id: id })
}
self.setUserId(id)
})
peer.on("connection", function(dataConnection) {
self.initialiseChannel(dataConnection)
})
}
connectToPeer(uid) {
this.initialiseChannel(this.peer.connect(uid))
}
initialiseChannel(dataConnection) {
var self = this
dataConnection.on("open", function() {
Moritz Langenstein
committed
//console.log("Connected to peer " + dataConnection.peer)
self.peers.set(dataConnection.peer, dataConnection)
self.userJoined(dataConnection.peer, "master")
})
dataConnection.on("data", function(data) {
Moritz Langenstein
committed
//console.log("Message from peer " + dataConnection.peer + ":", data)
self.receiveMessage(dataConnection.peer, data)
})
dataConnection.on("close", function() {
Moritz Langenstein
committed
//console.log("Disconnected from peer " + dataConnection.peer)
self.peers.delete(dataConnection.peer)
self.userLeft(dataConnection.peer)
this.peer.destroy()
this.peers = new Map()
super.disconnect()
}
reconnect() {
this.initialiseConnection()
send(uid, message) {
Moritz Langenstein
committed
//console.log("Sending message", message, "to " + uid)
var self = this
var send = function() {
// check if the clients still exists
var peer = self.peers.get(uid)
if (peer) {
try {
peer.send(message)
} catch (error) {
setTimeout(send, 500)
}
}
}
// try to send the message
send()
}
broadcast(message) {
Moritz Langenstein
committed
//console.log("Broadcasting message", message)
for (const uid of this.peers.keys()) {
this.send(uid, message)
}
}