Skip to content

Instantly share code, notes, and snippets.

@AcidLeroy
Created July 19, 2019 13:41
Show Gist options
  • Save AcidLeroy/773a32df223812decd3f424ed8532b54 to your computer and use it in GitHub Desktop.
Save AcidLeroy/773a32df223812decd3f424ed8532b54 to your computer and use it in GitHub Desktop.
The index code for the browser
/* eslint no-console: ["error", { allow: ["log"] }] */
/* eslint max-nested-callbacks: ["error", 5] */
'use strict'
const domReady = require('detect-dom-ready')
const createNode = require('./create-node')
const pull = require('pull-stream')
const PeerId = require('peer-id')
const PeerInfo = require('peer-info')
const listenerId = {
id: 'QmSjxSywvJrMFP8JrywsaNcqMsq9RgB99fQA13DasNyEqS',
pubKey: 'CAASpgIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDCX5qj3/g8LZ1TnJ6SnTxMILhOLP1CCdf1zsNI70Rek/WaD2hpIrq85du/S9EncPyXR5QIwSJZLcQxFUQvO1/YOGBkdbnHcXqPn2xpNVRmlrs9Ot81yC5XD9ceTr3WH1NKjcg5RiI6uuRtqFiZB24FFTTdWgH/Po+89/7QdLXRVObdlpFSEEtaoQuirLeztv5TYzeSIv8kgK5BmKq0AXZ6v0qaJ3rlKP2DfcxpD7tViscBxmVi01kzD/6djM8Rz4oCcAgTTWO7pnwfGb3bkdPZpu9LCu9P6b4IbC8UB6eFQi5hUw9YxIjDif+crGT/zby+g00oNyCLvtsZBaM3o2jhAgMBAAE='
}
domReady(() => {
const myPeerDiv = document.getElementById('my-peer')
const swarmDiv = document.getElementById('swarm')
createNode((err, node) => {
if (err) {
return console.log('Could not create the Node, check if your browser has WebRTC Support', err)
}
node.on('peer:discovery', (peerInfo) => {
console.log('Discovered a peer:', peerInfo.id.toB58String())
})
node.on('peer:connect', (peerInfo) => {
const idStr = peerInfo.id.toB58String()
console.log('Got connection to: ' + idStr)
const connDiv = document.createElement('div')
connDiv.innerHTML = 'Connected to: ' + idStr
connDiv.id = idStr
swarmDiv.append(connDiv)
PeerId.createFromJSON(listenerId).then(id => {
if (err) throw err
let peerInfo = new PeerInfo(id)
peerInfo.multiaddrs.add(`/dns4/star-signal.cloud.ipfs.team/tcp/443/wss/p2p-webrtc-star/p2p/${listenerId.id}`)
console.log("info = ", peerInfo)
node.dialProtocol(peerInfo, '/api', (err, conn) => {
console.log('dialed!!')
if (err) { throw err }
pull(pull.values(['Hello', ' ', 'p2p', ' ', 'world', '!']), conn)
})
}
)
})
node.on('peer:disconnect', (peerInfo) => {
const idStr = peerInfo.id.toB58String()
const el = document.getElementById(idStr)
el && el.remove()
})
node.start((err) => {
if (err) {
return console.log(err)
}
const idStr = node.peerInfo.id.toB58String()
const idDiv = document
.createTextNode('Node is ready. ID: ' + idStr)
myPeerDiv.append(idDiv)
console.log('Node is listening o/')
// NOTE: to stop the node
// node.stop((err) => {})
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment