Created
August 7, 2018 14:32
-
-
Save vaibhav6233m/58b5ca82719c5df037327adcfc126136 to your computer and use it in GitHub Desktop.
FindProviders functionality.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
node.files.add([Buffer.from(contentText)], { // find the contentText hash | |
onlyHash: true | |
}, (err, filesAdded) => { | |
if (err) { | |
return console.log(err) | |
} | |
const hash = filesAdded[0].hash | |
console.log("Searching for " + hash) | |
node.dht.findprovs(hash, (err, provInfos) => { // DHT findproviders | |
if (err) { | |
console.log("############Error in Findprovs.") | |
return //console.log(err) | |
} | |
console.log(provInfos) | |
provInfos.forEach(element => { | |
if (element.Type != 4 || !element.Responses["0"].ID || element.Responses["0"].ID === nodeIdB58) { //checking if it is provider using Type:4 | |
return | |
} | |
let pingCount = 0 | |
element.ID = element.Responses["0"].ID | |
node.ping(element.ID, { | |
// count: , | |
// n: 2 | |
}, function (err, responses) { | |
if (err) { | |
return console.log("dial failed to " + element.ID) | |
} | |
if (pingCount > 0) { | |
return | |
} | |
pingCount = pingCount + 1 | |
console.log("Found Provider:===========>" + element.ID + " " + element.Type) | |
var topic = element.ID | |
const receiveMsg = (msg) => { | |
if (msg.data.toString() === "send-details") { | |
return | |
} | |
var response = JSON.parse(msg.data.toString()) | |
if (response.to === nodeIdB58 && response.title === "send-details-response") { | |
const receiveUnsubscribeMsg = (msg) => console.log(msg.toString()) | |
node.pubsub.unsubscribe(topic, receiveUnsubscribeMsg, (err) => { | |
if (err) { | |
return console.error(`failed to unsubscribe from ${topic}`, err) | |
} | |
console.log(`unsubscribed from ${topic}`) | |
}) | |
} | |
} | |
node.pubsub.subscribe(topic, receiveMsg, (err) => { | |
if (err) { | |
return console.error(`failed to subscribe to ${topic}`, err) | |
} | |
console.log(`subscribed to ${topic}`) | |
let msg = Buffer.from("send-details") | |
node.pubsub.publish(topic, msg, (err) => { | |
if (err) { | |
return console.error(`failed to publish to ${topic}`, err) | |
} | |
// msg was broadcasted | |
console.log(`published to ${topic}`) | |
}) | |
}) | |
}) | |
}); | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment