-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbrowser.js
98 lines (89 loc) · 2.46 KB
/
browser.js
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
88
89
90
91
92
93
94
95
96
97
98
const debug = console.log
// const debug = () => { }
function createWindowHashIfNotPresent() {
if (window.location.hash) return
const base58Chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
let array = new Uint8Array(20)
window.crypto.getRandomValues(array);
array = array.map(x => base58Chars.charCodeAt(x % base58Chars.length));
window.history.replaceState(null, null, '#' + String.fromCharCode.apply(null, array))
}
function newIPFS(cb) {
const ipfs = new Ipfs({
repo: String(Math.random() + Date.now()),
EXPERIMENTAL: { pubsub: true },
config: {
Addresses: {
Swarm: ['/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star']
}
}
// libp2p: {
// config: {
// dht: {
// enabled: true
// }
// }
// }
// relay: {
// enabled: true,
// hop: {enabled: true}
// }
})
// Wait for peers
ipfs.on('ready', () => {
const tryListPeers = () => {
ipfs.swarm.peers((err, peers) => {
if (err) throw err
debug('Peers', peers)
if (!peers || peers.length == 0) setTimeout(() => tryListPeers(), 1000)
else cb(ipfs)
})
}
tryListPeers()
})
}
function ipfsDirBase() {
return 'wis-poc-' + window.location.hash.substring(1)
}
function ipfsSubscribe(ipfs, handle, cb) {
ipfs.pubsub.subscribe(
ipfsDirBase(),
msg => handle(msg.data.toString('utf8')),
err => {
if (err) console.error('Failed subscribe', err)
else {
debug('Subscribe to ' + ipfsDirBase() + ' complete')
cb()
}
})
}
function ipfsPublish(ipfs, data, cb) {
ipfs.pubsub.publish(
ipfsDirBase(),
ipfs.types.Buffer.from(data),
err => {
if (err) console.error('Failed publish', err)
else {
debug('Publish complete')
cb()
}
})
}
function setupChatChannel(channel) {
const areaElem = document.getElementById('chat')
const messageElem = document.getElementById('message')
channel.onclose = () => areaElem.value += "**system** chat closed\n"
channel.onopen = () => {
messageElem.disabled = false
areaElem.value += "**system** chat started\n"
}
channel.onmessage = e => areaElem.value += '**them** ' + e.data + "\n"
messageElem.onkeypress = e => {
const message = messageElem.value
if (e.keyCode == 13 && message) {
messageElem.value = ''
areaElem.value += '**me** ' + message + "\n"
channel.send(message)
}
}
}