Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/src/webrtc.js
blob: 312afa38f10099adbea4893c0a89567b98d892bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

class WebRTC {
  constructor(server) {
    this.configuration = {iceServers: [{urls: 'stun:stun.l.google.com:19302'}]}
    this.server = server
    this.peerConnections = {}
    // generate an identity identifier
    const numbers = window.crypto.getRandomValues(new Uint8Array(4))
    const symbols = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
    this.identity = Array.prototype.slice.call(numbers).map(x => symbols[x % 62]).join('')
    // announce ourselves via the channel
    server.sendMessage({announce: true, sender: this.identity})
  }

  getPeerConnection(identity) {
    if (!(identity in this.peerConnections)) {
      const peerConnection = new RTCPeerConnection(this.configuration)
      this.peerConnections[identity] = peerConnection
    }
    return this.peerConnections[identity]
  }

  handleMessage(msg) {
    const self = this
    var peerConnection
    // ignore our own messages
    if (msg.sender === self.identity || !msg.sender) { return }
    if (msg.announce && !(msg.sender in self.peerConnections)) {
      // handle new announce message by sending an offer
      peerConnection = self.getPeerConnection(msg.sender)
      peerConnection.createOffer().then(offer => {
        peerConnection.setLocalDescription(offer).then(x => {
          self.server.sendMessage({offer: offer, sender: self.identity, receipient: msg.sender})
        })
      })
    } else if (msg.offer && msg.receipient === self.identity) {
      // handle offers for us and answer
      peerConnection = self.getPeerConnection(msg.sender)
      peerConnection.setRemoteDescription(new RTCSessionDescription(msg.offer))
      peerConnection.createAnswer().then(answer => {
        peerConnection.setLocalDescription(answer).then(function () {
          self.server.sendMessage({answer: answer, sender: self.identity, recipient: msg.sender})
        })
      })
    } else if (msg.answer && msg.recipient === self.identity && msg.sender in self.peerConnections) {
      // handle answers to offers
      peerConnection = self.getPeerConnection(msg.sender)
      peerConnection.setRemoteDescription(new RTCSessionDescription(msg.answer)).then(x => {})
    }
  }
}

module.exports = WebRTC