-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbrowser-offer.html
87 lines (84 loc) · 3.11 KB
/
browser-offer.html
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<!DOCTYPE html>
<html>
<head>
<title>WebRTC IPFS Signaling Offerer</title>
<script src="https://unpkg.com/[email protected]/dist/index.min.js"></script>
<!-- <script src="js-ipfs.min.js"></script> -->
<script src="browser.js"></script>
</head>
<body>
<h3>WebRTC IPFS Signaling Offerer</h3>
<div>
<strong>URL to answer:</strong>
<a id="answerUrl"></a>
<button id="regenerate">Restart and Regenerate</button>
</div>
<hr />
<div>
<label for="chat">Chat:</label>
<textarea id="chat" style="width: 100%" rows="15" placeholder="(waiting for chat to start)" readonly></textarea>
<div style="display: flex">
<label for="message">Send Message: </label>
<input id="message" type="text" style="flex: 1" disabled>
</div>
</div>
<script>
// Make a random URL hash if not given
createWindowHashIfNotPresent()
// Grab the URL, replace offer w/ answer
const answerUrl = window.location.href.replace('offer.html', 'answer.html')
const answerUrlAnchor = document.getElementById('answerUrl')
answerUrlAnchor.href = answerUrl
answerUrlAnchor.innerText = answerUrl
// Refresh if asked
document.getElementById('regenerate').onclick = () => {
window.location.hash = ''
location.reload()
}
// Create IPFS and do everything else once ready
newIPFS(ipfs => {
// Create new RTC conn
const pc = new RTCPeerConnection({
// Could have a TURN server too, not worth it for the demo
iceServers: [{ urls: 'stun:stun.l.google.com:19302'}]
})
// Setup the chat channel
setupChatChannel(pc.createDataChannel('chat'))
// Add the handlers
pc.oniceconnectionstatechange = e => debug('RTC connection state change', pc.iceConnectionState)
pc.onicecandidate = e => {
// No candidate means we're done
if (e.candidate === null) {
// Keep publishing the offer until we receive the answer
let gotAnswer = false
ipfsSubscribe(
ipfs,
data => {
if (gotAnswer) return
const obj = JSON.parse(data)
debug('Received data', obj)
if (obj.type == 'answer') {
gotAnswer = true
pc.setRemoteDescription(new RTCSessionDescription(obj))
}
},
() => {
// This is the callback meaning subscribe completed so we can start sending offers
const sendOffer = () => {
if (gotAnswer) return
debug('Sending offer')
ipfsPublish(ipfs, JSON.stringify(pc.localDescription), () => {
// Try again in a couple of seconds
setTimeout(() => sendOffer(), 2000)
})
}
sendOffer()
})
}
}
pc.onnegotiationneeded = e =>
pc.createOffer().then(d => pc.setLocalDescription(d)).catch(console.error)
})
</script>
</body>
</html>