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

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

      const webrtc = new LioWebRTC({
        url: this.webrtcOptions.url,
        dataOnly: true,
        network: {
          minPeers: 4,
          maxPeers: 8,
        },
      this.webrtc = webrtc
      const self = this
      webrtc.on("ready", () => {
        webrtc.joinRoom(self.webrtcOptions.room)
      })

      webrtc.on("joinedRoom", () => {
        const id = webrtc.getMyId()
        for (var f of self.userEventListeners) {
          f({ action: "userID", id: id })
        }

      // Cannot use createdPeer here as y-js will then try to send data before the channel is open
      webrtc.on("channelOpen", (dataChannel, peer) => {
        self.userJoined(peer.id, "master")
      webrtc.on("receivedPeerData", (type, message, peer) => {
        self.receiveMessage(peer.id, message)
      webrtc.on("removedPeer", (peer) => {
        self.userLeft(peer.id)
    connectToPeer(/*uid*/) {
      // currently deprecated
      super.disconnect()
    }

    reconnect() {
      this.webrtc.whisper(this.webrtc.getPeerById(uid), "y-js", message)
      this.webrtc.shout("y-js", message)

    isDisconnected() {
      return false
    }
  }

  Y.extend("webrtc", WebRTC)
}

Nayeem Rahman's avatar
Nayeem Rahman committed
export default extend
if (typeof Y !== "undefined") {
  extend(Y)
}