Skip to content
Snippets Groups Projects
index.js 2.7 KiB
Newer Older
/* global Y */
"use strict"

var {
} = 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

      var peer = new Peer({
        host: this.webrtcOptions.host,
        port: this.webrtcOptions.port,
      this.peer = peer
      var self = this
      this.peers = new Map()

      peer.on("open", function(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() {
        //console.log("Connected to peer " + dataConnection.peer)

        self.peers.set(dataConnection.peer, dataConnection)
        self.userJoined(dataConnection.peer, "master")
      })

      dataConnection.on("data", function(data) {
        //console.log("Message from peer " + dataConnection.peer + ":", data)

        self.receiveMessage(dataConnection.peer, data)
      })

      dataConnection.on("close", function() {
        //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() {
      //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) {
      //console.log("Broadcasting message", message)
      for (const uid of this.peers.keys()) {
        this.send(uid, message)
      }
    }

    isDisconnected() {
      return false
    }
  }

  Y.extend("webrtc", WebRTC)
}

module.exports = extend
if (typeof Y !== "undefined") {
  extend(Y)
}